algorithm-base/animation-simulation/数组篇/剑指offer3数组中重复的数.md

104 lines
3.6 KiB
Java
Raw Normal View History

2021-03-20 08:30:29 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:48:03 +00:00
#### [ Offer 03. ](https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/)
2021-03-17 11:49:19 +00:00
****
n nums 0n-1
1
[2, 3, 1, 0, 2, 5, 3]
2 3
2021-03-20 04:32:33 +00:00
#### **HashSet**
2021-03-17 11:49:19 +00:00
****
HashSet HashSet set
****
```java
class Solution {
public int findRepeatNumber(int[] nums) {
// HashSet
HashSet<Integer> set = new HashSet<Integer>();
for (int x : nums) {
//发现某元素存在,返回
if (set.contains(x)) {
return x;
}
//存入哈希表
set.add(x);
}
return -1;
}
}
```
2021-03-20 04:32:33 +00:00
#### ****
2021-03-17 11:49:19 +00:00
****
****
![offer3](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/剑指offer3数组中重复的数.2p6cd5os0em0.gif)
****
Java Code:
2021-03-17 11:49:19 +00:00
```java
class Solution {
public int findRepeatNumber(int[] nums) {
if (nums.length == 0) {
return -1;
}
for (int i = 0; i < nums.length; ++i) {
while (nums[i] != i) {
//发现重复元素
if (nums[i] == nums[nums[i]]) {
return nums[i];
}
//置换,将指针下的元素换到属于他的索引处
int temp = nums[i];
nums[i] = nums[temp];
nums[temp] = temp;
}
}
return -1;
}
}
```
C++ Code:
```cpp
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
if(nums.empty()) return 0;
int n = nums.size();
for(int i = 0; i < n; ++i){
while(nums[i] != i){
if(nums[i] == nums[nums[i]]) return nums[i];
swap(nums[i], nums[nums[i]]);
}
}
return -1;
}
};
```