287. Find the Duplicate Number

**Description**Hints**Submissions**Solutions

Total Accepted: 67370
Total Submissions: 157182
Difficulty: Medium
Contributor: LeetCode

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:
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.

Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Hide Company Tags
Bloomberg
Hide Tags
Binary Search Array Two Pointers
Hide Similar Problems
(H) First Missing Positive (E) Single Number (M) Linked List Cycle II (E) Missing Number

** 解題思路 **
兩種解法:

  • Two pointer
  • Binary search

Two Pointer

Use Two pointers, O(n) Time , O(1) space, without changing the input array
The main idea is the same with problem Linked List CycleII, https://leetcode.com/problems/linked-list-cycle-ii/.
Use two pointers the fast and the slow. The fast one goes forward two steps each time, while the slow one goes only step each time. They must meet the same item when slow==fast. In fact, they meet in a circle, the duplicate number must be the entry point of the circle when visiting the array from nums[0].
Next we just need to find the entry point. We use a point(we can use the fast one before) to visit form begining with one step each time, do the same job to slow. When fast==slow, they meet at the entry point of the circle. The easy understood code is as follows.

Binary Search

Binary Search, O(nlog(n)) , O(1) space, without changing the input array
Let count be the number of elements in the range 1 .. mid,
-If count > mid, then there are more than mid elements in the range 1 .. mid and thus that range contains a duplicate.
If count <= mid, then there are n+1-count elements in the range mid+1 .. n. That is, at least n+1-mid elements in a range of size n-mid. Thus this range must
contain a duplicate.
鴿巢原理确徙,又名狄利克雷抽屜原理炎滞、鴿籠原理
其中一種簡單的表述法為:
若有n個籠子和n+1只鴿子置鼻,所有的鴿子都被關在鴿籠里,那么至少有一個籠子有至少2只鴿子香浩。
另一種為:
若有n個籠子和kn+1只鴿子濒翻,所有的鴿子都被關在鴿籠里丁溅,那么至少有一個籠子有至少k+1只鴿子。

/*   Solution 1:  Two pointers,  O(n) Time , O(1) space, without changing the input array 
      The main idea is the same with problem Linked List Cycle II,https://leetcode.com/problems/linked-list-cycle-ii/. 
        Use two pointers the fast and the slow. The fast one goes forward two steps each time, while the slow one goes only step each time. They must meet the same item when slow==fast. In fact, they meet in a circle, the duplicate number must be the entry point of the circle when visiting the array from nums[0]. 
        Next we just need to find the entry point. We use a point(we can use the fast one before) to visit form begining with one step each time, do the same job to slow. When fast==slow, they meet at the entry point of the circle. The easy understood code is as follows.
    */
    public int findDuplicate(int[] nums) {
      if (nums.length > 1) {
          int slow = nums[0];
          int fast = nums[nums[0]];
          while (slow != fast) {
              slow = nums[slow];
              fast = nums[nums[fast]];
          }
          fast = 0;
          while (fast != slow) {
              fast = nums[fast];
              slow = nums[slow];
          }
          return slow;
      }
      return -1;
        
    }
  
    
    /*
     Solution 2:  Binary Search,  O(nlog(n)) , O(1) space, without changing the input array 
     Let count be the number of elements in the range 1 .. mid,
     If count > mid, then there are more than mid elements in the range 1 .. mid and thus that range contains a duplicate.
     If count <= mid, then there are n+1-count elements in the range mid+1 .. n. That is, at least n+1-mid elements in a range of size n-mid. Thus this range must contain a duplicate.
    */
    public int findDuplicateBinarySearch(int[] nums) {
      int start = 0, end = nums.length - 1;
      while (start <= end) {
          int mid = start + (end - start) / 2;
          int count = 0;
          for (int i : nums) {
              if (i <= mid) {
                  count++;
              }
          }
          if (count <= mid){
              start = mid + 1;
          } else {
              end = mid - 1;
          }
      }
      return start;
    }
    
    // find the only one duplicate, occur once
    public int findOnlyOneDuplicate(int[] nums) {
      // sum (nums[0] , nums[n]) 
      int sum = 0;
      int secondSum = 0;
      
      for (int i = 0; i < nums.length; i++) {
          sum += nums[i];
      }
      
      secondSum = (1 + nums.length - 1) * (nums.length - 1) / 2;
      return sum - secondSum;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末义锥,一起剝皮案震驚了整個濱河市柳沙,隨后出現的幾起案子拌倍,更是在濱河造成了極大的恐慌数初,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異薄料,居然都是意外死亡,警方通過查閱死者的電腦和手機谷市,發(fā)現死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進店門创泄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事箕速♂阌” “怎么了?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我秸架,道長揍庄,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任东抹,我火速辦了婚禮蚂子,結果婚禮上,老公的妹妹穿的比我還像新娘缭黔。我一直安慰自己食茎,他們只是感情好,可當我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布馏谨。 她就那樣靜靜地躺著别渔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪惧互。 梳的紋絲不亂的頭發(fā)上哎媚,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天,我揣著相機與錄音喊儡,去河邊找鬼拨与。 笑死,一個胖子當著我的面吹牛管宵,可吹牛的內容都是我干的。 我是一名探鬼主播攀甚,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼箩朴,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了秋度?” 一聲冷哼從身側響起炸庞,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎荚斯,沒想到半個月后埠居,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡事期,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年滥壕,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片兽泣。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡绎橘,死狀恐怖,靈堂內的尸體忽然破棺而出唠倦,到底是詐尸還是另有隱情称鳞,我是刑警寧澤涮较,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站冈止,受9級特大地震影響狂票,放射性物質發(fā)生泄漏。R本人自食惡果不足惜熙暴,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一闺属、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧怨咪,春花似錦屋剑、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至匠楚,卻和暖如春巍膘,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背芋簿。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工峡懈, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人与斤。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓肪康,卻偏偏與公主長得像,于是被迫代替她去往敵國和親撩穿。 傳聞我的和親對象是個殘疾皇子磷支,可洞房花燭夜當晚...
    茶點故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內容