35. Search Insert Position

来源:互联网 发布:unity3d ios 交互 编辑:程序博客网 时间:2024/05/29 07:50


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

 public static int searchInsert_1(int[] nums, int target) {//太繁琐            int[] nums1=new int[nums.length+1];                for(int i=0;i<nums.length;i++)                {                if(nums[i]==target)                return i;                else                 {                nums1[i]=nums[i];                }                }                nums1[nums.length]=target;                                Arrays.sort(nums1);                for(int i=0;i<nums1.length;i++)                {                if(nums1[i]==target)                return i;                }                return -1;            }
 public static int searchInsert_2(int[] nums,int target)//二分查找思路            {            int low=0;            int high=nums.length-1;            while(low<=high)            {            int mid=(low+high)/2;            if(target==nums[mid])            {            return mid;            }            else if(target<nums[mid])            {            high=mid-1;            }            else            {            low=mid+1;            }            }            return low;            }            


0 0
原创粉丝点击