LeetCode 287 -Find the Duplicate Number ( JAVA )
2016-04-11 11:05
489 查看
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.
![](https://img-blog.csdn.net/20160411110437050?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
总结:对数组进行排序,再进行比较。
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.
public class Solution { public int findDuplicate(int[] nums) { Arrays.sort(nums); int duplicate = 0; for(int i = 0 ; i < nums.length-1 ; i++){ if(nums[i] == nums[i+1]){ duplicate = nums[i]; } } return duplicate; } }
总结:对数组进行排序,再进行比较。
相关文章推荐
- java字符、字节、位
- ubuntu下 验证码出不来问题 java.lang.Error: Probable fatal error:No fonts found.
- Myeclipse 的配置与使用
- java嵌套类和内部类
- Java基础
- Java String的一些方法使用
- java中equals和==以及toString
- JAVA回调机制
- java中super和this
- Java编程介绍
- JAVA学习---集合系列---ArrayList
- 2016华为机试题(java版):两个大数相减的程序(运行成功)
- eclipse中svn的使用
- java中final和static
- java垃圾回收和收尾
- 在java应用程序和web应用中的相对路径问题
- eclipse导入html、js、xml报错的问题
- Spring进阶之路(1)-Spring核心机制:依赖注入/控制反转
- Eclipse+Struts2的简单应用
- Java 开发包下载网址