數組和矩陣(1)——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.segmentfault

Note:less

  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.

https://segmentfault.com/a/1190000003817671#articleHeader4spa

考慮:指針

  1. 暴力求解,選擇一個數,看有沒有重複的;
  2. 哈希表
  3. 排序後遍歷
  4. 二分法
  5. 設置快慢指針,映射找環法
 1 public class Solution {
 2     public int findDuplicate(int[] nums) { //映射找環
 3         int n = nums.length - 1;
 4         int pre = 0;
 5         int last = 0;
 6         do {
 7             pre = nums[pre];
 8             last = nums[nums[last]];
 9         } while(nums[pre] != nums[last]);
10         last = 0;
11         while(nums[pre] != nums[last]) {
12             pre = nums[pre];
13             last = nums[last];
14         }
15         return nums[last];
16     }
17 }
相關文章
相關標籤/搜索