35. 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

Already Pass Answer:

public int SearchInsert(int[] nums, int target)
        {
            int top = 0;
            int mid = nums.Length / 2;
            int fin = nums.Length - 1;
            //(1)
            int result = -1;
            
            while (top <= fin)
            {
                if (target != nums[mid])
                {
                    if (top == fin)
                    {
                        if (target > nums[mid])
                        {
                            result = mid + 1;
                            break;
                        }
                        else
                        {
                            result = mid;
                            break;
                        }
                    }
                    else
                    {
                        //(2)
                        if (target > nums[mid])
                        {
                            top = mid == fin?mid:mid+1;
                        }
                        else
                        {
                            fin = mid == top?mid:mid-1;
                        }
                        mid = (top + fin) / 2;
                    }
                }
                else
                {
                    result = mid;
                    break;
                }

            }
            return result;
        }

解题思路
1.主要的思路为二分法的查找
2.数组界限的判断
有待思考
(1)result值是否可以去掉
(2)界限的判断更简单的方法

你可能感兴趣的:(35. Search Insert Position)