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

LeetCode 2

时间:2017-11-13 14:07:07      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:target   public   ret   sort   while   dex   search   个人   insert   

No1

  

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.

个人:

public int searchInsert(int[] nums, int target) {
		for(int i=0;i<nums.length;i++){
			if(nums[i]>=target){
				return i;
			}
		}
		return nums.length;

	}

  优秀代码:

 public int searchInsert(int[] A, int target) {
        int low = 0, high = A.length-1;
        while(low<=high){
            int mid = (low+high)/2;
            if(A[mid] == target) return mid;
            else if(A[mid] > target) high = mid-1;
            else low = mid+1;
        }
        return low;
    }

LeetCode 2

标签:target   public   ret   sort   while   dex   search   个人   insert   

原文地址:http://www.cnblogs.com/KingIceMou/p/7825626.html

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