[Leetcode] Find the Duplicate Number, Solution

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.
Note:
  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

[Thoughts]
這題想清楚了就不難,想不清楚就麻煩。

假設數組A長度是n, 裏面存儲1到n的整數,那麼很清楚,咱們能夠在按照A[i] = i+1,進行排序。可是如今有n+1個整數,並且至少有一個數字存在冗餘。若是咱們仍然按照A[i] = i+1來排序數組的話,那麼當發現A[i]上已是i+1的值時,說明咱們已經找到了冗餘數了。

舉個例子,


簡單的說,就是遍歷數組的同時,按照A[i]應該放到A[A[i]]原則,進行swap,第一個沒法swap的數字就是所求。


[Code]
1:  class Solution {  
2: public:
3: int findDuplicate(vector<int>& nums) {
4: int length = nums.size();
5: for(int i =0; i< length; i++) {
6: if(nums[i] == i+1) {
7: continue;
8: }
9: int oldIndex = i;
10: int newIndex = nums[i]-1;
11: while(nums[oldIndex] != oldIndex +1 ) {
12: if(nums[oldIndex] == nums[newIndex] ) {
13: return nums[oldIndex];
14: }
15: int temp = nums[newIndex];
16: nums[newIndex] = nums[oldIndex];
17: nums[oldIndex] = temp;
18: newIndex = nums[oldIndex] -1;
19: }
20: }
21: }
22: };

github: https://github.com/codingtmd/leetcode/blob/master/src/Find_the_Duplicate_Number.cpp
相關文章
相關標籤/搜索