【Lintcode】633. Find the Duplicate Number

題目地址:

https://www.lintcode.com/problem/find-the-duplicate-number/description

給定一個數組,長度爲N+1N+1,數組中的數字範圍是[1,N][1,N]的整數,有且僅有一個數字出現了多於11次,要求將其求出。

思路是鏈表求環。參考https://blog.csdn.net/qq_46105170/article/details/104018748。代碼如下:

public class Solution {
    /**
     * @param nums: an array containing n + 1 integers which is between 1 and n
     * @return: the duplicate one
     */
    public int findDuplicate(int[] nums) {
        // write your code here
        int slow, fast;
        slow = fast = 0;
        do {
            slow = nums[slow];
            fast = nums[nums[fast]];
        } while (slow != fast);
        
        // 接下來用鏈表求環的入口的辦法求重複數字。
        int p = 0;
        while (p != slow) {
            p = nums[p];
            slow = nums[slow];
        }
    
        return p;
    }
}

時間複雜度O(n)O(n),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章