Problem
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.
class Solution { public int findDuplicate(int[] nums) { int start = 0, end = nums.length-1; while (start <= end) { int mid = start + (end-start)/2; if (count(nums, mid) <= mid) { start = mid+1; //numbers no larger than mid <= mid, so mid is safe, search second half } else end = mid-1; //numbers less than mid > mid, so there is duplicate in first half } return start; //when start > end, } private int count(int[] nums, int k) { int count = 0; for (int num: nums) { if (num <= k) count++; } return count; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/69307.html
摘要:復雜度思路每次通過二分法找到一個值之后,搜索整個數組,觀察小于等于這個數的個數。考慮,小于這個位置的數的個數應該是小于等于這個位置的。要做的就是像找中的環一樣,考慮重復的點在哪里。考慮用快慢指針。代碼把一個指針放回到開頭的地方 LeetCode[287] Find the Duplicate Number Given an array nums containing n + 1 in...
Problem 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 nu...
摘要:暴力法復雜度時間空間思路如果不用空間的話,最直接的方法就是選擇一個數,然后再遍歷整個數組看是否有跟這個數相同的數就行了。二分法復雜度時間空間思路實際上,我們可以根據抽屜原理簡化剛才的暴力法。 Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is bet...
Problem Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms o...
摘要:前言從開始寫相關的博客到現在也蠻多篇了。而且當時也沒有按順序寫現在翻起來覺得蠻亂的。可能大家看著也非常不方便。所以在這里做個索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關的博客到現在也蠻多篇了。而且當時也沒有按順序寫~現在翻起來覺得蠻亂的。可能大家看著也非常不方便。所以在這里做個索引嘻嘻。 順序整理 1~50 1...
閱讀 3575·2021-09-22 10:52
閱讀 1595·2021-09-09 09:34
閱讀 1997·2021-09-09 09:33
閱讀 764·2019-08-30 15:54
閱讀 2679·2019-08-29 11:15
閱讀 722·2019-08-26 13:37
閱讀 1676·2019-08-26 12:11
閱讀 2983·2019-08-26 12:00