leetcode上關於數組元素與下標存在關係的幾道題的解題方法總結

關於一個數組存儲元素與下標存在關係中出現幾種情況的算法解答

1.448. Find All Numbers Disappeared in an Array (https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/

題意:數組長度爲n 裏面存儲元素爲1到n 但部分元素重複  要求找出缺少的元素
   Input:
       [4,3,2,7,8,2,3,1]

   Output:
       [5,6]

解題關鍵爲:利用下標與數組元素關係相等,先使用第一個for循環使數組中出現的元素的下標處的值統一加上n,

                  在利用第二個for循環判斷數組中元素<n的則爲沒出現的(小於n的原因是第一個for循環爲改變改值)

class Solution {
   public List<Integer> findDisappearedNumbers(int[] nums) { 
        List<Integer> res = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < nums.length; i ++) nums[(nums[i]-1) % n] += n;
        for (int i = 0; i < nums.length; i ++) if (nums[i] <= n) res.add(i+1); 
       //爲什麼是i+1 因爲未修改的元素的數字就是那個下標+1  數字與下標加1一一對應 第一個for只是爲了證明那個元                  素被修改了
        return res;
    }
}
 

 

2. 287. Find the Duplicate Number

題意:數組長度爲n,裏面存儲元素爲1到n-1 有一個元素重複 找出重複元素

Input: [1,3,4,2,2]
Output: 2

 

Input: [3,1,3,4,2]
Output: 3
public class Solution {
    public int findDuplicate(int[] nums) {
        if (nums == null || nums.length < 2) return 0;
        int fast = nums[nums[0]];
        int slow = nums[0];
        
        while (fast != slow) {
            fast = nums[nums[fast]];
            slow = nums[slow];
        }
        
        fast = 0;
        while (slow != fast) {
            slow = nums[slow];
            fast = nums[fast];
        }
        
        return fast;
    }
}

 

3.   217. Contains Duplicate(https://leetcode.com/problems/contains-duplicate/

題意:有重複元素返回true 沒有則返回false

Input: [1,2,3,1]
Output: true
Input: [1,2,3,4]
Output: false

由於只需要返回true與false所以代碼比較簡單

class Solution {
   public  boolean containsDuplicate(int[] nums) {
		 Set<Integer> set = new HashSet<Integer>();
		 for(int i : nums)
			 if(!set.add(i))// if there is same
				 return true; 
		 return false;
	 }
}

 

4.   268. Missing Number(https://leetcode.com/problems/missing-number/

題意:數組中無重複元素,數組長度爲n   則元素爲0到n  但缺少了部分元素    最後輸出缺少的數字

Input: [3,0,1]
Output: 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8

           解題關鍵在於異或的運用 a^a^b =b  xor的初值設置爲nums.length也是很值得思考的  最終還是在利用數組元素與數組下標的關係來解題

數組元素爲  3   0   1 

數組下標爲  0   1   2   3 (元素與下標異或)由於在for循環中i並沒有取到nums.length也就是3 所以xor初值要設置爲3

class Solution {
    public int missingNumber(int[] nums) {
      int xor = nums.length; //等於nums.length的原因是 異或之後剛好差這個元素 
                            //因爲i在for循環中只能到nums.length-1
	  for (int i = 0; i < nums.length; i++) {
		xor = xor ^ i ^ nums[i];
	  }
	return xor ;
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章