LeetCode 題解(252) : 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.
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.
這道題太高深了,參見這裡的解法
C++版:
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int low = 0, high = nums.size() - 1;
while(low <= high) {
int mid = (low + high) / 2;
int count = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] <= mid)
count++;
}
if(count > mid)
high = mid - 1;
else
low = mid + 1;
}
return low;
}
};
Python版:
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) / 2
cnt = sum(x <= mid for x in nums)
if cnt > mid:
high = mid - 1
else:
low = mid + 1
return low
相關文章
- [LeetCode] Find the Duplicate NumberLeetCode
- LeetCode-Find the Duplicate NumberLeetCode
- leetcode287: Find the Duplicate NumberLeetCode
- [leetcode] 252. Meeting Rooms 解題報告LeetCodeOOM
- LeetCode - 解題筆記 - 8 - Palindrome NumberLeetCode筆記
- leetcode 掃描線專題 06-leetcode.252 meeting room 力扣.252 會議室LeetCodeOOM力扣
- leetcode刷題--Happy NumberLeetCodeAPP
- leetcode刷題--Number of 1 BitsLeetCode
- [LeetCode] 252、會議室LeetCode
- LeetCode #252 - Meeting RoomsLeetCodeOOM
- Leetcode 252 Meeting RoomsLeetCodeOOM
- [LeetCode 252] Meeting RoomsLeetCodeOOM
- LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance??LeetCode
- LeetCode 第 9 題(Palindrome Number)LeetCode
- LeetCode 第 65 題(Valid Number)LeetCode
- leetcode刷題--Excel Sheet Column NumberLeetCodeExcel
- LeetCode252 Meeting RoomsLeetCodeOOM
- leetcode-252-Meeting RoomsLeetCodeOOM
- LeetCode 第 191 題 (Number of 1 Bits)LeetCode
- LeetCode 252. 會議室(排序)LeetCode排序
- 【leetcode】252 會議室(陣列)LeetCode陣列
- LeetCode解題報告 452. Minimum Number of Arrows to Burst Balloons [medium]LeetCode
- Leetcode Number of islandsLeetCode
- LeetCode:Largest NumberLeetCode
- LeetCode-Python-252. 會議室LeetCodePython
- Leetcode 252. Meeting Rooms (Easy) (cpp)LeetCodeOOM
- 解決 Inkscape 報錯 Duplicate 問題
- ARC173A Neq Number 題解
- LeetCode-Remove Duplicate LettersLeetCodeREM
- [LeetCode] Third Maximum NumberLeetCode
- LeetCode-Strobogrammatic NumberLeetCode
- LeetCode-Largest NumberLeetCode
- LeetCode-Number of IslandsLeetCode
- Leetcode Valid NumberLeetCode
- leetcode Palindrome NumberLeetCode
- Leetcode Single NumberLeetCode
- LeetCode 252. Meeting Rooms (Java版; Easy)LeetCodeOOMJava
- LeetCode 252. Meeting Rooms(會議室)LeetCodeOOM