Advertisement
sweet1cris

Untitled

Jan 9th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. // version 1: find the first position >= target
  2. public class Solution {
  3.     public int searchInsert(int[] A, int target) {
  4.         if (A == null || A.length == 0) {
  5.             return 0;
  6.         }
  7.         int start = 0, end = A.length - 1;
  8.        
  9.         while (start + 1 < end) {
  10.             int mid = start + (end - start) / 2;
  11.             if (A[mid] == target) {
  12.                 return mid;
  13.             } else if (A[mid] < target) {
  14.                 start = mid;
  15.             } else {
  16.                 end = mid;
  17.             }
  18.         }
  19.        
  20.         if (A[start] >= target) {
  21.             return start;
  22.         } else if (A[end] >= target) {
  23.             return end;
  24.         } else {
  25.             return end + 1;
  26.         }
  27.     }
  28. }
  29.  
  30. // version 2: find the last position < target, return +1, 要特判一下target小于所有数组里面的元素
  31.  
  32. public class Solution {
  33.     public int searchInsert(int[] A, int target) {
  34.         if (A == null || A.length == 0) {
  35.             return 0;
  36.         }
  37.         int start = 0;
  38.         int end = A.length - 1;
  39.         int mid;
  40.        
  41.         if (target < A[0]) {
  42.             return 0;
  43.         }
  44.         // find the last number less than target
  45.         while (start + 1 < end) {
  46.             mid = start + (end - start) / 2;
  47.             if (A[mid] == target) {
  48.                 return mid;
  49.             } else if (A[mid] < target) {
  50.                 start = mid;
  51.             } else {
  52.                 end = mid;
  53.             }
  54.         }
  55.        
  56.         if (A[end] == target) {
  57.             return end;
  58.         }
  59.         if (A[end] < target) {
  60.             return end + 1;
  61.         }
  62.         if (A[start] == target) {
  63.             return start;
  64.         }
  65.         return start + 1;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement