版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83996430
一、Description
题目描述:
给定n + 1个数字,这些数字的范围在1 - n之间,在这些数字中有一个出现不止一次的数字,找出这个数字。
要求用O(1)的空间和少于O(n^2)的时间复杂度。
二、Analyzation
遍历这个数组,对于每个数字x,nums[x - 1]上的数字如果为正,则令其为相反数;如果nums[x - 1]上的数为负,则表示前面的数字中已经出现过当前数字,因此停止遍历,直接返回这个数即可。
三、Accepted code
class Solution {
public int findDuplicate(int[] nums) {
if (null == nums || 0 == nums.length) {
return 0;
}
int result = 0;
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]);
if (nums[index - 1] > 0) {
nums[index - 1] = - nums[index - 1];
} else {
result = index;
break;
}
}
return result;
}
}