287. Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
解法1 排序
先排序,然后依次判断前一个和后一个是不是一样的,一样的就返回该数,否则循环后返回-1
class Solution {
public int findDuplicate(int[] nums) {
Arrays.sort(nums);
int n=nums.length;
int r=0;
for(int i=0;i<n-1;i++)
{
if(nums[i]==nums[i+1]) return nums[i];
// break;
}
return -1;
}
}
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)-1):
if(nums[i]==nums[i+1]):
return nums[i]
return -1
解法2 set
set中不能有重复的元素,所以每次添加前都可以判断是不是在集合中,在就返回该元素,否则添加进去
class Solution(object):
def findDuplicate(self, nums):
se=set()
for i in range(len(nums)):
if nums[i] not in se:
se.add(nums[i])
else:
return nums[i]
return -1
class Solution {
public int findDuplicate(int[] nums) {
Set<Integer> se = new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
if(se.contains(nums[i])){
return nums[i];
}
else se.add(nums[i]);
}
return -1;
}
}