剑指 Offer 03. 数组中重复的数字
2021-03-07 本文已影响0人
7ccc099f4608
https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
image.png
(图片来源https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
)
| 日期 | 是否一次通过 | comment |
|---|---|---|
| 2021-03-07 | 0 |
/** 遍历 */
public int findRepeatNumber(int[] nums) {
if(nums == null || nums.length < 1) {
return -1;
}
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]);
}
}
return -1;
}
private void swap(int[] nums, int l, int r) {
int tmp = nums[l];
nums[l] = nums[r];
nums[r] = tmp;
}