Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
find-the-duplicate-number.cpp 1.72 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2015-09-28 16:39 +08:00 . Update find-the-duplicate-number.cpp
// Time: O(n)
// Space: O(1)
// Two pointers method, same as Linked List Cycle II.
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = nums[0];
int fast = nums[nums[0]];
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};
// Time: O(nlogn)
// Space: O(1)
// Binary search method.
class Solution2 {
public:
int findDuplicate(vector<int>& nums) {
int left = 1, right = nums.size();
while (left <= right) {
const int mid = left + (right - left) / 2;
// Get count of num <= mid.
int count = 0;
for (const auto& num : nums) {
if (num <= mid) {
++count;
}
}
if (count > mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
};
// Time: O(n)
// Space: O(n)
class Solution3 {
public:
int findDuplicate(vector<int>& nums) {
int duplicate = 0;
// Mark the value as visited by negative.
for (auto& num : nums) {
if (nums[abs(num) - 1] > 0) {
nums[abs(num) - 1] *= -1;
} else {
duplicate = abs(num);
break;
}
}
// Rollback the value.
for (auto& num : nums) {
if (nums[abs(num) - 1] < 0) {
nums[abs(num) - 1] *= -1;
} else {
break;
}
}
return duplicate;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助