LeetCode Daily Question 15

3 月 22 日 每日一题


题目:287. Find the Duplicate Number

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

1
2
3
4
5
6
7
8
Example 1:

Input: nums = [1,3,4,2,2]
Output: 2
Example 2:

Input: nums = [3,1,3,4,2]
Output: 3

思路

hashmap 应该算这道题的暴力解法,等肝完 281project 之后可能会在这里更新其他方法。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int findDuplicate(vector<int>& nums) {
unordered_map<int, int> counts;
for(int i = 0; i < nums.size(); i ++){
auto &iter = counts[nums[i]];
iter++;
if(iter == 2)
return nums[i];
}
return -1;
}
};
  1. 3 月 22 日 每日一题
    1. 题目:287. Find the Duplicate Number
    2. 思路
    3. 代码