[LeetCode#35]Search Insert Position

The problem:

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

My analysis:

The question has already assumed ther are no duplicates in the array.

In reality, we should take care of this case!



The key idea behind this solution is to use invariant that :

Before we exit from the while loop, the target must meet the condition : A[front] < target < B[end]



When we exit from the while loop, only two conditions are possible:

1. the target was successfully found out. 

2. the front pointer move beyond the end pointer, or the end pointer move before the front pointer. 

Note: the mid pointer now is at the position when front == end. (the latest position for mid)

    a. if front pointer move beyond the end pointer, means the target larger than the last mid, it should be palced after the           right last mid.

    b. if end pointer move before the front pointer, means the target smaller than the last mid, it should be palced at the the         mid's position (not before mid: mid - 1), all elements(includ mid) should be move backward one node.



The stop state:

end < target < front, the position to insert target is front.

Before reaching the final state:

[elements smaller than target], front(mid), end, [elements larger than target]

Iff mid < target, we forward front one step. 

[elements smaller than target],element smaller than target, front (mid) end,  [elements larger than target]

2.1 Iff mid < target, we forward front one step.

Now front is pointing at the first element this is larger than target.

2.2 Iff mid > target, we bacward end one step.

Now front keep the same, pointing at the first element that is larger than target.

The solution:

public class Solution {

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

        if (A.length == 0)

            return -1;

            

        int front = 0;

        int end = A.length - 1;

        int mid = -1;

        

        while (front <= end) {

            mid = (front + end) / 2;

            if (A[mid] == target) {

                return mid;

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

                front = mid + 1;

            } else {

                end = mid - 1;

            }

        }

        return front;

    }

}

 

你可能感兴趣的:(LeetCode)