Search Insert Position

https://oj.leetcode.com/problems/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.

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

 

Hide Tags
  Array Binary Search
 
解题思路:
这道题目比较简单。从头遍历,发现比目标大或者等于的数字,说明是插入的位置,或者等于,立刻返回其index。如果找到最后还没有,则说明应该在length的位置插入,直接返回i。时间复杂度为O(n)。
public class Solution {

    public int searchInsert(int[] A, int target) {

    //int target_index = 0;

    int i = 0;

    for(; i < A.length; i++){

        if(A[i] >= target){

            return i;

            //break;

        }

    }

    //if(i == A.length && A[A.length - 1] < target){

      //  target_index = A.length;

    //}

    return i;

    }

}

也可以用二分查找,复杂度减少为O(lgn)。

public class Solution {

    public int searchInsert(int[] A, int target) {

        int leftIndex = 0;

        int rightIndex = A.length - 1;

        int midIndex = 0;



        while(leftIndex < rightIndex){

            midIndex = (leftIndex + rightIndex) / 2;

            if(target == A[midIndex]){

                return midIndex;

            }else if(target < A[midIndex]){

                rightIndex = midIndex;

            }else{

                leftIndex = midIndex + 1;

            }

        }

        midIndex = (leftIndex + rightIndex) / 2;

        if(target > A[midIndex]){

            return midIndex + 1;

        }else{

            return midIndex;

        }

    }

}

update 2015/05/30:

public class Solution {

    public int searchInsert(int[] nums, int target) {

        if(nums.length == 0) {

            return 0;

        }

        int start = 0, end = nums.length - 1;

        while(start <= end) {

            int mid = (start + end) / 2;

            if(nums[mid] == target) {

                return mid;

            }

            if(nums[mid] > target) {

                end = mid - 1;

            }

            if(nums[mid] < target) {

                start = mid + 1;

            }

        }

        return start;

    }

}

 

你可能感兴趣的:(position)