Find Missing Term in Arithmetic Progression 等差数列缺失项

查找等差数列中的缺失项.

e.g.Input: arr[] = {2, 4, 8, 10, 12, 14} 

Output: 6

Input: arr[] = {1, 6, 11, 16, 21, 31};

Output: 26.

采用binary search. 若是arr[mid] - arr[left] == (mid - left) * diff, 说明missing 部分在mid右侧.

否则missing部分在包括mid的左侧.

Time complexity: O(logn). Space: O(1).

 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         try{
 5             int [] arr1 = {2, 4, 8, 10, 12, 14};
 6             int [] arr2 = {1, 6, 11, 16, 21, 31};
 7             int [] arr3 = {1, 6};
 8             System.out.println(findMissing(arr1));
 9             System.out.println(findMissing(arr2));
10             
11             System.out.println(findMissing(arr3));
12             
13         }catch(IllegalArgumentException e){
14             System.out.println(e.getMessage());
15         }    
16     }
17     
18     private static int findMissing(int [] arr) throws IllegalArgumentException{
19         if(arr == null || arr.length < 3){
20             throw new IllegalArgumentException("Invalid input!");
21         }
22         int len = arr.length;
23         int l = 0;
24         int r = len-1;
25         int diff = (arr[r] - arr[l])/len;
26         System.out.println(diff);
27         while(l <= r){
28             int mid = l+(r-l)/2;
29             if(arr[mid] - arr[l] == (mid-l)*diff){
30                 l = mid+1;
31             }else{
32                 r = mid;
33             }
34         }
35         return arr[r] - diff;
36     }
37 }

 

 

posted @ 2016-03-30 04:14  Dylan_Java_NYC  阅读(394)  评论(0编辑  收藏  举报