题目原址
https://leetcode.com/problems/find-the-duplicate-number/description/
题目描述
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.
Example1:
Input: [1,3,4,2,2]
Output: 2
Example2:
Input: [3,1,3,4,2]
Output: 3
Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than O(n2).
- There is only one duplicate number in the array, but it could be repeated more than once.
解题思路
给定一个数组,数组中包含n + 1个元素,数组的元素值范围为1 - n
,因此,其中包含重复的元素,现在要求找到这个重复的元素并返回。
因为只有一个元素是重复的,所以这个题的思路就是:把每个元素的值 - 1
作为新的数组元素的下标值,找到一个元素,就将新数组元素对应的值设置为 -1,遍历完整个数组,直到找到重复的元素为止。
AC代码
class Solution {
public int findDuplicate(int[] nums) {
int ret = 0;
int[] num = new int[nums.length - 1];
for(int i = 0; i < nums.length; i++) {
if(!(num[nums[i] - 1] == -1))
num[nums[i] - 1] = -1;
else
ret = nums[i];
}
return ret;
}
}