[LeetCode]287. Find the Duplicate Number
来源:互联网 发布:数据口径 编辑:程序博客网 时间:2024/06/05 18:24
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.
思路:我想到两种一种是最简单的,遍历然后找此元素前边的所有元素是否有相同的,O(n2)的时间复杂度,还有一个种是用数组存每个数的次数,如果找到大于1次的就返回,O(n)的时间,但是费空间
O(n2):
public class Solution { public int findDuplicate(int[] nums) { for(int i=0;i<nums.length;i++){ for(int j=0;j<i;j++){ if(nums[i]==nums[j]){ return nums[i]; } } } return 0; } }
O(n):
public class Solution { public int findDuplicate(int[] nums) { int[] times=new int[nums.length+1]; for(int i=0;i<nums.length;i++){ times[nums[i]]++; if(times[nums[i]]>1){ return nums[i]; } } return 0; }}
0 0
- [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
- 51 Nod 夹克老爷的愤怒
- eclipse wildfly 运行中断
- Android topbar 实例········································································
- hdu 2571 命运
- Mybatis框架的注解问题
- [LeetCode]287. Find the Duplicate Number
- Linux下进度条的编写和实现(gcc 和 Makefile)
- JVM运行时数据区域
- HFOIer4.22题目
- JdbcUtils工具类(c3p0+DbUtils优化)
- easyUI的中文乱码问题
- 逆向工程核心原理学习笔记(五):实战“打补丁方法”修改字符串
- 手把手git教程(10)--github如何删除一个repository(仓库)
- CheckBox的简单使用