LeetCode:35. Search Insert Position(Easy)

1. 原题链接

https://leetcode.com/problems/search-insert-position/description/

2. 题目要求

给定一个已经排好序的数组和一个目标值,假设该数组中没有重复值,返回目标值在数组中的插入位置下标。

3. 解题思路

利用折半查找法定位插入的位置

4. 代码实现

 1 public class SearchInsertPosition35 {
 2     public static void main(String[] args) {
 3         int[] nums = {1, 3, 5, 6};
 4         System.out.println(searchInsert(nums, 7));
 5     }
 6 
 7     public static int searchInsert(int[] nums, int target) {
 8         int left = 0, right = nums.length - 1;
 9         while (left <= right) {
10             int mid = (left + right) / 2;
11             if (nums[mid] == target) return mid;
12             else if (nums[mid] > target) right = mid - 1;
13             else left = mid + 1;
14         }
15         return left;
16     }
17 }

 

posted @ 2018-01-05 13:17  一只敲码的猫  阅读(148)  评论(0编辑  收藏  举报