数组长度为len,数组元素的范围是0到len-1,找出数组的重复元素
public static int findDuplicate(int[] nums) { int len = nums.length; //注意这里的for循环写法,在交换元素后,i没有增加,还要继续进行判断 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; //这里将temp放到对应的位置上 } else { i++; } } return -1; } public static void main(String[] args) { int[] nums = { 1, 2, 4, 2, 3 , 6 , 5}; System.out.println(findDuplicate(nums)); }