Traversal

题目描述[原题链接][https://www.acwing.com/problem/content/description/14/]

给定一个长度为 n 的整数数组 nums,数组中所有的数字都在 0∼n−1 的范围内。

数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。

请找出数组中任意一个重复的数字。

注意:如果某些数字不在 0∼n−1 的范围内,或数组中不包含重复数字,则返回 -1;

样例

1
2
3
给定 nums = [2, 3, 5, 4, 3, 2, 6, 7]。

返回 2 或 3。

算法描述

遍历数组,使用Set记录,遍历时判断是否有与set中重复的元素,有的话更新ans,如果数据满足条件要求的条件,添加到set容器中,最后返回ans;

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int duplicateInArray(vector<int>& nums) {
unordered_map<int,int> mp;
int ans = -1;
int n = nums.size();
for(int i=0;i<n;i++){
if(nums[i]>=0&&nums[i]<=n-1){
if(ans==-1){
++mp[nums[i]];
if(mp[nums[i]]==2)ans=nums[i];
}
}
else return -1;
}
return ans;
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int duplicateInArray(int[] nums) {
Set<Integer> set = new HashSet<>();

int ans = -1;

for(int i=0;i<nums.length;i++){
if(set.contains(nums[i])){
ans = nums[i];
}
if(nums[i]>=0&&nums[i]<nums.length)
set.add(nums[i]);
else return -1;
}

return ans;

}
}