數組中的重複數字

  • 找出數組中重複的數字。

    “在一個長度爲 n 的數組 nums 裏的所有數字都在 0~n-1 的範圍內。”數組中某些數字是重複的,但不知道有幾個數字重複了,也不知道每個數字重複了幾次。請找出數組中任意一個重複的數字。

    示例 1:

    輸入:
    [2, 3, 1, 0, 2, 5, 3]
    輸出:2 或 3

限制:

2 <= n <= 100000

import java.util.*;
class Solution {
    public int findRepeatNumber(int[] nums) {
    /*  超時
        Arrays.sort(nums);
        if(nums.length == 0) return 0;
        ArrayList<Integer> list =  new ArrayList<>();
        for(int i : nums){
            if(!list.contains(i)){
                list.add(i);
            }else{
                return i;
            }
                
        }
        return 0;
    */
    /*
    //根據數組大小的範圍,利用hash的思想
        if (nums.length == 0) return 0;
        int[] num = new int[nums.length];
        for (int i : nums) {
             num[i]++;
            if (num[i] > 1){
                return i;
            }
        }
      return 0;
      */
	//原地哈希,節省空間
      for (int i = 0; i < nums.length; i++) {
          while (i != nums[i]){
              if (nums[i] == nums[nums[i]]) return nums[i];
               swap(nums, nums[i], i);
          }
      }
      return 0;
    }
    public void swap(int[] arr, int i, int j){
      int temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
}

執行用時 :1 ms, 在所有 Java 提交中擊敗了93.64%的用戶
內存消耗 :49.5 MB, 在所有 Java 提交中擊敗了100.00%的用戶

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