[leetcode] 287.Find the Duplicate Number
2015-09-28 13:25
169 查看
题目:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate element 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 extra space.
Your runtime complexity should be less than O(n2).
题意:
给定一个含有n+1个元素的整数数组,包含的元素的大小是1到n。证明最少有一个元素重复了。假设只有一个重复元素,找出这个重复元素。
思路:
因为这个数组的特点非常明显,元素的大小是在1到n之间,而且只有一个元素是重复出现的。那么如果我们存储nums[i] = i + 1,那么对于重复的那个元素j,两个元素都想存放在nums[j-1]中。所以我们可以将元素放入它应该放的位置,比如k应该放在数组的下标k-1的位置。我们遍历数组,将扫描到的数字k放到它应该放的位置k-1,可以将当前元素与nums[k-1]交换,继续将当前位置上交换得到的值放到它应该出现的位置。循环的终止条件是当前位置存放的值就是应该存放的数字,或者当前位置想把数字k交换到它的指定位置时,发现那个位置已经存放了一个k,如果是遇到这个终止条件,那么将需要返回这个值k。
以上所述。
代码如下:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate element 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 extra space.
Your runtime complexity should be less than O(n2).
题意:
给定一个含有n+1个元素的整数数组,包含的元素的大小是1到n。证明最少有一个元素重复了。假设只有一个重复元素,找出这个重复元素。
思路:
因为这个数组的特点非常明显,元素的大小是在1到n之间,而且只有一个元素是重复出现的。那么如果我们存储nums[i] = i + 1,那么对于重复的那个元素j,两个元素都想存放在nums[j-1]中。所以我们可以将元素放入它应该放的位置,比如k应该放在数组的下标k-1的位置。我们遍历数组,将扫描到的数字k放到它应该放的位置k-1,可以将当前元素与nums[k-1]交换,继续将当前位置上交换得到的值放到它应该出现的位置。循环的终止条件是当前位置存放的值就是应该存放的数字,或者当前位置想把数字k交换到它的指定位置时,发现那个位置已经存放了一个k,如果是遇到这个终止条件,那么将需要返回这个值k。
以上所述。
代码如下:
class Solution { public: int findDuplicate(vector<int>& nums) { if(nums.empty())return -1; for(int i = 0; i < nums.size(); i++) { while(nums[i] != i + 1 && nums[nums[i] - 1] != nums[i])swap(nums[nums[i] - 1], nums[i]); if(nums[i] != i + 1)return nums[i]; } } };
相关文章推荐
- JavaScript内置对象
- UML之时序图(Sequence Diagram)
- js中null 和undefined的区别
- smtplib.SMTPDataError: 554, 'DT:SPM
- iOS开发 ----- 网络请求5 ----- NSURLsession实现上传数据
- vim的复制粘贴小结
- 二叉树的还原(先序+中序)
- Oracle 动态语句小例 Trim表中栏位 (不积跬步,无以至千里)
- Android NotificationManager 和Notification的使用总结 转
- 允许Android对于飞行模拟器
- Android KeyCode列表
- ORA-12641: Authentication service failed to initialize
- 抓包工具charles使用教程指南
- boost::asio网络编程(同步)
- 抓包工具charles使用教程指南
- java环境变量配置,卸载
- HDU 3416 Marriage Match IV(中等,好题) [最大流]最短路+最大流
- linux查看磁盘使用情况 查看文件夹大小
- YUM
- 缩略图到大图浏览转场