CS-Notes icon indicating copy to clipboard operation
CS-Notes copied to clipboard

3. 数组中重复的数字

Open MakenChan opened this issue 3 years ago • 1 comments

`

public int duplicate(int[] nums) { for (int i = 0; i < nums.length; i++) { while (nums[i] != i) { if (nums[i] == nums[nums[i]]) { return nums[i]; } swap(nums, i, nums[i]); } //这里为什么还需要交换,这个是多余的 swap(nums, i, nums[i]); } return -1; }

private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; }`

MakenChan avatar Jun 28 '21 06:06 MakenChan

确实是多余的,i == nums[i], 即swap参数 i==j,指向的都是同一个元素

Jack9610 avatar Sep 14 '21 08:09 Jack9610