Seawolf 发表于 2019-8-30 09:27:31

leetcode 35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: , 5
Output: 2
Example 2:

Input: , 2
Output: 1
Example 3:

Input: , 7
Output: 4
Example 4:

Input: , 0
Output: 0


class Solution {
    public int searchInsert(int[] nums, int target) {
      
      int start = 0;
      
      int end = nums.length -1;
      
      while( start <=end){
            
            int mid = (start + end) / 2;
            
            if(nums == target){
               
                return mid;
            }
            
            else if(nums > target){
               
                end = mid -1 ;
            }
            
            else if(nums < target){
               
                start = mid + 1;
            }
      }
      
      return Math.abs(-end - 1);
      
    }
}
页: [1]
查看完整版本: leetcode 35. Search Insert Position