码迷,mamicode.com
首页 > 其他好文 > 详细

Search Insert Position 解答

时间:2015-09-14 07:02:48      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

Question

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.

Here are few examples.
[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

Solution 1 -- Naive

Iterate the array and compare target with ith and (i+1)th element. Time complexity O(n).

 1 public class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         if(nums==null) return 0;
 4         if(target <= nums[0]) return 0;
 5         for(int i=0; i<nums.length-1; i++){
 6             if(target > nums[i] && target <= nums[i+1]){
 7                 return i+1;
 8             }
 9         }
10         return nums.length;
11     }
12 }

Solution 2 -- Binary Search

If the target number doesn‘t exist in original array, then after iteration, it must be pointed by low pointer.

Time complexity O(log(n))

 1 public class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         if (nums == null || nums.length == 0)
 4             return 0;
 5         int start = 0, end = nums.length - 1, mid = (end - start) / 2 + start;
 6         while (start <= end) {
 7             mid = (end - start) / 2 + start;
 8             if (nums[mid] == target)
 9                 return mid;
10             else if (nums[mid] < target)
11                 start = mid + 1;
12             else
13                 end = mid - 1;
14         }
15         return start;
16     }
17 }

 

Search Insert Position 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4804009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!