LeetCode_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

Hide Tags
 Array Binary Search
翻译:
Code:

/**
 * 
 */
package From21;

import java.util.Arrays;

/**
 * @author MohnSnow
 * @time 2015年6月16日 下午2:02:52
 * 
 */
public class LeetCode35 {

	/**
	 * @param argsmengdx
	 *            -fnst
	 */
	//372msA --- 一次性编写通过-- 删掉判断i相等之后---384msA
	public static int searchInsert(int[] nums, int target) {
		int len = nums.length;
		int i = 0;
		int j = nums.length - 1;
		if (nums[0] >= target || len == 0)
			return 0;
		if (nums[j] < target)
			return len;
		while (i <= j) {
			if (i + 1 < len && nums[i + 1] < target) {
				i++;
			}
			if (i + 1 < len && nums[i + 1] >= target) {
				return i + 1;
			}
			if (j - 1 >= 0 && nums[j - 1] < target) {
				return j;
			}
			if (j - 1 >= 0 && nums[j - 1] >= target) {
				j--;
			}
		}
		return 0;
	}

	public static void main(String[] args) {
		//int[] nums = { 3, 5, 5, 7, 7, 8, 8, 8, 10 };
		int[] nums = { 1, 3, 5, 6 };
		int target = 5;
		System.out.println("寻找插入:" + searchInsert(nums, target));

	}

}




你可能感兴趣的:(LeetCode,算法,LeetCode,java)