1. 程式人生 > >不修改數組找出重復的數字

不修改數組找出重復的數字

rgs i++ print 一個數 所有 amp start println code

題目:

在一個長度為n+1的數組裏面的所有數字都在1-n的範圍內,所以數組至少存在了一個數字是重復的。請找出數。中任意一個重復的數字,但不能修改輸入的數組。

解答:

 1 public class Solution {
 2 
 3     public static void main(String[] args) {
 4         int arr = {2,3,5,4,3,2,6,7};
 5         System.out.println(getDuplication(arr, arr.length))
 6     }
 7 
 8     public
static int getDuplication(int[] arr, int length) { 9 if(arr == null || length <= 0) { 10 return -1; 11 } 12 13 // 1-n 14 int start = 1; 15 int end = length-1; 16 17 while(start >= end) { 18 int mid = (end-start)>>1 + start;
19 20 int count = countRange(arr, length, start, mid); 21 22 if(end == start) { 23 if(count > 1) { 24 return start; 25 } else { 26 break; 27 } 28 } 29 30 if
(count > (mid-start+1)) { 31 end = mid; 32 } else { 33 start = mid + 1; 34 } 35 } 36 37 return -1; 38 39 } 40 41 private static int countRange(int[] arr, int length, int start, int mid) { 42 if(arr == null) { 43 return 0; 44 } 45 46 int count = 0; 47 for(int i = 0; i < length; i++) { 48 // 49 if(arr[i] >= start && arr[i] <= mid) { 50 count++; 51 } 52 } 53 54 return count; 55 } 56 }

不修改數組找出重復的數字