3. 数组中重复的数字[java]
2020-12-13 04:59
标签:null 重复数 turn tps als href question div ranking 在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 时间复杂度 O(N),空间复杂度 O(1) 对于范围0到n-1的数组,最好方法是将数字0放到位置0,数字1放到位置1,以此类推. 若当前遍历到的数字若与之前遍历过的数重复,即为重复数; 例如上面的例子,当遍历到第5个数nums[4]=2时,数组内顺序为:[0,1,2,3,2,5],此时,nums[4]==nums[2],即nums[4]为重复数 3. 数组中重复的数字[java] 标签:null 重复数 turn tps als href question div ranking 原文地址:https://www.cnblogs.com/zslhg903/p/11127202.html题目描述 在线编程
Input:
{2, 3, 1, 0, 2, 5}
Output:
2
解题思路
public boolean duplicate(int[] nums, int length, int[] duplication) {
if (nums == null || length )
return false;
for (int i = 0; i ) {
while (nums[i] != i) {
if (nums[i] == nums[nums[i]]) {
duplication[0] = nums[i];
return true;
}
swap(nums, i, nums[i]);
}
}
return false;
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
上一篇:Java垃圾回收