代码实现:
package j2; /** * 不修改数组找出重复的数字 * Created by admin on 2019/5/14. */ public class FindDuplicate3 { public static void main(String[] args) { int arr[] = {2,3,5,4,3,2,6,7}; System.out.println(duplicate(arr,arr.length)); } public static int duplicate(int[] arr,int len){ if (arr == null || arr.length<= 0) { return -1; } int start=1; int end = len-1; while (start <= end) { int mid = ((end-start)>>1)+start; //统计每区间里数字的数目 int count = countRange(arr,len,start,mid); if (end == start) { if (count>1) { return start; } else { break; } } if (count > (mid-start+1)) { end = mid; } else { start = mid+1; } } return -1; } /** * 统计区间中数字的数目 * @param arr * @param len * @param start * @param end * @return */ private static int countRange(int[] arr, int len, int start, int end) { int result = 0; if (arr == null || arr.length<=0) { return 0; } for (int i=0;i<len;i++) { if (arr[i]>=start&& arr[i] <= end) { result++; } } return result; } }
原文地址:https://www.cnblogs.com/airycode/p/10867442.html
时间: 2024-10-20 15:43:45