【LeetCode】Search Insert Position

【Description】

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: [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 4:

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

【AC code】

一、暴力法  时间复杂度:O(n)

1 class Solution {
2     public int searchInsert(int[] nums, int target) {
3         for (int i = 0; i < nums.length; i++) {
4             if (nums[i] >= target) return i;
5         }
6         return nums.length;
7     }
8 }
View Code

 

二、二分查找法  时间复杂度:O(logn)

 1 class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         int arrlen = nums.length;
 4         if (nums[arrlen - 1] < target) return arrlen;
 5         int left = 0, right = arrlen - 1;
 6         while (left <= right) {
 7             int mid = left + (right - left) / 2;
 8             if (nums[mid] > target) right = mid - 1;
 9             else if (nums[mid] < target) left = mid + 1;
10             else return mid;
11         }
12         return left;
13     }
14 }
View Code

 

posted @ 2019-09-12 11:04  ___Moongazer  阅读(99)  评论(0编辑  收藏  举报