1. 程式人生 > >找出長度為n的數組中重復的一個數字(數字範圍在0~n-1) 不采用hashmap

找出長度為n的數組中重復的一個數字(數字範圍在0~n-1) 不采用hashmap

static 一個 str for each light println 循環 pub

要求不采用hashmap

	public static void main(String[] args) {
		int[] nums = { 1, 2, 4, 3, 0 };
		System.out.println(findDuplicate(nums));
		Arrays.stream(nums).forEach(System.out::print);
	}

	public static int findDuplicate(int[] nums) {
		int len = nums.length;
		//註意這裏的for循環寫法,在交換元素後,還要進行判斷
		for (int i = 0; i < len;) {
			if (nums[i] != i) {
				// 不相等
				int temp = nums[i];
				if (temp == nums[temp]) {
					return temp;
				}
				nums[i] = nums[temp];
				nums[temp] = temp;
			} else {
				i++;
			}
		}
		return -1;
	}

  

找出長度為n的數組中重復的一個數字(數字範圍在0~n-1) 不采用hashmap