Find the duplicate Number (鸽巢原理) leetcode java
2015-12-18 10:29
639 查看
问题描述:
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.
分析:有n + 1数,其中每个数的范围都是1-n,可以证明这n+1个数中至少有两个数是相同的(鸽巢原理)。假设正好只有两个数是相同的,请找出重复出现的数。
方法一:快速排序,时间复杂度O(nlogn)
方法二:二分查找
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.
分析:有n + 1数,其中每个数的范围都是1-n,可以证明这n+1个数中至少有两个数是相同的(鸽巢原理)。假设正好只有两个数是相同的,请找出重复出现的数。
方法一:快速排序,时间复杂度O(nlogn)
public int findDuplicate(int[] nums) { int n = nums.length; //长度 quickSort(nums,0,n - 1); //快速排序,时间复杂度小于O(n*n) for(int i = 0; i < n - 1; i++){ if(nums[i] == nums[i + 1] ) return nums[i]; } return -1; } //快速排序 public static void quickSort(int[] nums,int left,int right){ int dp; if (left < right) { dp = partition(nums, left, right); quickSort(nums, left, dp - 1); quickSort(nums, dp + 1, right); } } //划分 public static int partition(int n[], int left, int right) { int pivot = n[left]; while (left < right) { while (left < right && n[right] >= pivot) right--; if (left < right) n[left++] = n[right]; while (left < right && n[left] <= pivot) left++; if (left < right) n[right--] = n[left]; } n[left] = pivot; return left; }
方法二:二分查找
//二分查找 :若小于mid的数有mid个,则在upperPart查找,否则,在lowerPart查找 public static int findDuplicate(int[] nums){ int n = nums.length - 1; // 总共 n+1 个元素 int low = 1; //数组中可能的最小值 int high = n; //数组中可能的最大值 int mid = 0; while(low < high){ mid = low + (high - low) / 2; //取中间值 int c = count(mid, nums); //统计小于mid的元素 if(c <= mid){//重复值应该在upperPart low = mid + 1; }else { //重复值应该在lowerPart high = mid - 1; } } return low; } public static int count(int mid,int[] nums){ int c = 0; for (int i = 0; i < nums.length; i++) { if(nums[i] <= mid) c++; } return c; }
相关文章推荐
- 【Java EE 学习 74 上】【数据采集系统第六天】【使用Jfreechart的统计图实现】【Jfreechart的基本使用方法】
- eclipse安装svn插件
- 为什么HikariCP被号称为性能最好的Java数据库连接池,如何配置使用
- Spring 简单读取文件
- java 读取 写入 csv 文件
- JAVA / Scala Multi Class in One Source File
- 轻量级JavaEE企业应用实战(八)
- java Semaphore(信号量)
- Java后台如何接收并处理前台传过来的json格式的数组参数
- Java计算上传文件大小
- Binary Tree Level Order Traversal - leetcode - java
- Top 16 Java 应用类 - 这些功能再也不用自己写了
- 通过 EWS JAVA API读取exchange邮件
- Eclipse 安装 Valgrind 插件(解决安装完找不到的问题)
- java——Arrays.asList()方法
- Arrays.asList java.lang.UnsupportedOperationException 异常
- Symmetric Tree leetcode java
- Java之—— SSH整合常见错误
- 实习过程学习(4):java跨项目访问
- spring aop 错误解决无法查询到internalAutoProxyCreator