【LeetCode从零单刷】Find the Duplicate Number
2015-10-10 09:51
435 查看
题目:
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
There is only one duplicate number in the array, but it could be repeated more than once.
解答:
其实我第一个想法就是排序,如果前后相同就说明元素重复了。满足上面的所有要求,然后AC了……
二分法:遍历一遍数组,大于中间数的个数如果多于 (n / 2) 则说明多出来的数在大于中间数的那部分中,同理也可能在小于中间数的那部分中。这样每次只关注某一半的数据,搜索一半而已;
映射找环法:使用快慢两个指针遍历,非常巧妙
以上两种解法具体见:传送门
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.
解答:
其实我第一个想法就是排序,如果前后相同就说明元素重复了。满足上面的所有要求,然后AC了……
class Solution { public: int findDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); int ans = nums[0]; for(int i = 0; i< nums.size() - 1; i++) { if(nums[i] == nums[i+1]) ans = nums[i]; } return ans; } };其实这道题还有很多奇妙的解法:
二分法:遍历一遍数组,大于中间数的个数如果多于 (n / 2) 则说明多出来的数在大于中间数的那部分中,同理也可能在小于中间数的那部分中。这样每次只关注某一半的数据,搜索一半而已;
映射找环法:使用快慢两个指针遍历,非常巧妙
以上两种解法具体见:传送门
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息