35. Search Insert Position

原题链接:https://leetcode.com/problems/search-insert-position/description/
这道题目直接上二分查找即可:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) throws InterruptedException {
        Solution s = new Solution();
        /**
         * Example 1:

         Input: [1,3,5,6], 5
         Output: 2
         Example 2:

         Input: [1,3,5,6], 2
         Output: 1
         Example 3:

         Input: [1,3,5,6], 7
         Output: 4
         Example 1:

         Input: [1,3,5,6], 0
         Output: 0

         */
        System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 5));
        System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 2));
        System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 7));
        System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 0));
    }

    public int searchInsert(int[] nums, int target) {
        if (nums.length == 0) {
            return 0;
        }
        if (target < nums[0]) {
            return 0;
        }
        if (target > nums[nums.length - 1]) {
            return nums.length;
        }

        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int middle = (start + end) / 2;
            if (target > nums[middle]) {
                start = middle + 1;
            } else if (target < nums[middle]) {
                end = middle - 1;
            } else {
                return middle;
            }
        }

        return start;
    }

}
posted @ 2018-03-15 11:06  optor  阅读(109)  评论(0编辑  收藏  举报