1. 程式人生 > 其它 >【LeetCode】287. Find the Duplicate Number 尋找重複數(Medium)(JAVA)

【LeetCode】287. Find the Duplicate Number 尋找重複數(Medium)(JAVA)

技術標籤:Leetcodeleetcodejava演算法面試資料結構

【LeetCode】287. Find the Duplicate Number 尋找重複數(Medium)(JAVA)

題目地址: https://leetcode.com/problems/find-the-duplicate-number/

題目描述:

Given an array of integers nums containingn + 1 integers where each integer is in the range [1, n] inclusive.

There is only one duplicate number in nums, return thisduplicate number.

Follow-ups:

  1. How can we prove that at least one duplicate number must exist in nums?
  2. Can you solve the problem withoutmodifyingthe array nums?
  3. Can you solve the problem usingonly constant, O(1) extra space?
  4. Can you solve the problem with runtime complexity less than O(n^2)?

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2

Example 2:

Input: nums = [3,1,3,4,2]
Output: 3

Example 3:

Input: nums = [1,1]
Output: 1

Example 4:

Input: nums = [1,1,2]
Output: 1

Constraints:

  • 2 <= n <= 3 * 10^4
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.

題目大意

給定一個包含n + 1 個整數的陣列nums,其數字都在 1 到 n之間(包括 1 和 n),可知至少存在一個重複的整數。假設只有一個重複的整數,找出這個重複的數。

說明:

  1. 不能更改原陣列(假設陣列是隻讀的)。
  2. 只能使用額外的 O(1) 的空間。
  3. 時間複雜度小於 O(n^2) 。
  4. 陣列中只有一個重複的數字,但它可能不止重複出現一次。

解題方法

  1. 這道題找的是重複的元素,而且僅存在一個重複的元素(重複出現的次數 >= 2),
  2. 如果按照 i -> nums[i] -> nums[nums[i]] 連線起來 (i 從 0 開始,nums[i] != 0),存在重複元素,肯定就會形成一個環
  3. 這一道問題就變成了找出環的入口節點的問題
  4. 可用快慢指標的來解決
class Solution {
    public int findDuplicate(int[] nums) {
        int fast = nums[nums[0]];
        int slow = nums[0];
        while (fast != slow) {
            fast = nums[nums[fast]];
            slow = nums[slow];
        }
        fast = 0;
        while (fast != slow) {
            fast = nums[fast];
            slow = nums[slow];
        }
        return slow;
    }
}

執行耗時:0 ms,擊敗了100.00% 的Java使用者
記憶體消耗:38.5 MB,擊敗了65.28% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新