找尋數組中重複的元素

給定一個整數數組,1≤[i]≤n(n =數組的大小),其中一些元素出現兩次其他的只出現一次。

找到所有兩次出現在這個數組的元素。

你能做它沒有額外的空間,在O(n)運行時?

example

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]


查找重複的元素

 public List<Integer> findDuplicates(int[] nums) {
      List<Integer> res = new ArrayList();
      for(int num : nums){
        int n = Math.abs(num);
        int index = n - 1;
        if(nums[index] < 0) res.add(n);
        nums[index] = -nums[index];
      }
      return res;
    }

 
想法是把數組的元素反轉爲負數,後面 遇到相同下標的就是之前出現過的。


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