Leetcode 287. Find the Duplicate Number
来源:互联网 发布:手机dj软件 编辑:程序博客网 时间:2024/06/18 09:12
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.
1.time: O(n), space: O(1)
In analogy with #142 Linked List Cycle:
The main idea is the same with problem Linked List Cycle II,https://leetcode.com/problems/linked-list-cycle-ii/. Use two pointers the fast and the slow. The fast one goes forward two steps each time, while the slow one goes only step each time. They must meet the same item when slow==fast. In fact, they meet in a circle, the duplicate number must be the entry point of the circle when visiting the array from nums[0]. Next we just need to find the entry point. We use a point(we can use the fast one before) to visit form begining with one step each time, do the same job to slow. When fast==slow, they meet at the entry point of the circle. The easy understood code is as follows.
public int findDuplicate(int[] nums) { int slow = nums[0]; int fast = nums[nums[0]]; while (slow != fast) { slow = nums[slow]; fast = nums[nums[fast]]; } fast = 0; while (fast != slow) { fast = nums[fast]; slow = nums[slow]; } return slow; }
2.time:O(nlogn) space: O(1)
sort array first , then find duplicate
public int findDuplicate(int[] nums) { Arrays.sort(nums); int result = 0; for(int i = 0; i < nums.length - 1; i++){ if(nums[i] == nums[i+1]){ result = nums[i]; break; } } return result; }
- [leetcode] 287.Find the Duplicate Number
- [leetcode] 287. Find the Duplicate Number
- <LeetCode OJ> 287. Find the Duplicate Number
- Leetcode 287. Find the Duplicate Number
- Leetcode - 287. Find the Duplicate Number
- [LeetCode]287. Find the Duplicate Number
- LeetCode 287. Find the Duplicate Number
- 【leetcode】287. Find the Duplicate Number
- 【leetcode】287. Find the Duplicate Number
- leetcode 287. Find the Duplicate Number
- LCP287 LeetCode 287. Find the Duplicate Number
- [Leetcode]287. Find the Duplicate Number
- Leetcode题解 287. Find the Duplicate Number
- [LEETCODE] 287. Find the Duplicate Number
- [LeetCode] 287. Find the Duplicate Number
- <leetcode>287. Find the Duplicate Number
- [leetcode]287.Find the Duplicate Number
- LeetCode 287. Find the Duplicate Number
- CSS总结——2
- 【HTML5学习笔记】28:CSS3文本效果
- js获取本月开始时间和结束时间
- zoj2318 getout(计算几何)
- HTTP协议下GET与POST的区别
- Leetcode 287. Find the Duplicate Number
- 分布式数据库架构及企业实践--基于Mycat中间件pdf
- MySQL袖珍参考手册(第2版)pdf
- XML入门指南pdf
- XML原理及应用pdf
- DB2 SQL性能调优秘笈pdf
- DB2安装手册pdf
- DB2上机操作指南word版
- Db2通用数据库-电子商务的基石word版