首页 > 编程语言 > 详细

Java [leetcode 35]Search Insert Position

时间:2015-11-15 17:41:07      阅读:195      评论:0      收藏:0      [点我收藏+]

题目描述:

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

解题思路:

使用二分法搜索,当出现相等的情况就返回该位置的值;否则结果是right < left;这表明在上一次循环中出现两种情况:1、mid位置的值大于target,则最后一次循环后right = mid - 1,所以插入的位置肯定为right + 1的位置;2、mid位置的值小于target,则最后一次循环后left = mid + 1,所以插入的位置肯定为right + 1。综上,代码如下所示:

代码如下:

public class Solution {
    public static int searchInsert(int[] nums, int target) {
		int left, right, mid;
		left = 0;
		right = nums.length - 1;

		while (left <= right) {
			mid = (left + right) / 2;
			if (nums[left] == target)
				return left;
			if (nums[right] == target)
				return right;
			if (nums[mid] == target)
				return mid;

			if (nums[mid] > target)
				right = mid - 1;
			else if (nums[mid] < target)
				left = mid + 1;
		}
		return right + 1;
	}
}

 

Java [leetcode 35]Search Insert Position

原文:http://www.cnblogs.com/zihaowang/p/4966833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!