Fork me on GitHub

search-insert-position

/**
*
* @author gentleKay
* 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
*
*给定排序数组和目标值,如果找到目标,则返回索引。
*如果没有,则返回按顺序插入索引的位置。
*您可以假定数组中没有重复项。
*这里有几个例子。
[1,3,5,6],5→2
[1,3,5,6],2→1
[1,3,5,6],7→4
[1,3,5,6],0→0
*
*/

方法一:

/**
 * 
 * @author gentleKay
 * 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
 *
 *给定排序数组和目标值,如果找到目标,则返回索引。
 *如果没有,则返回按顺序插入索引的位置。
 *您可以假定数组中没有重复项。
 *这里有几个例子。
		[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 class Main20 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] A = {};
		System.out.println(Main20.searchInsert(A, 0));
	}
	
	public static int searchInsert(int[] A, int target) {
		
		for (int i=0;i<A.length;i++) {
			if (A[i] >= target) {
				return i;
			}
		}
		return A.length;
    }
}

方法二:(原理是一样的)

package com.kay.sample01;

/**
 * 
 * @author gentleKay
 * 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
 *
 *给定排序数组和目标值,如果找到目标,则返回索引。
 *如果没有,则返回按顺序插入索引的位置。
 *您可以假定数组中没有重复项。
 *这里有几个例子。
		[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 class Main20 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] A = {};
		System.out.println(Main20.searchInsert(A, 0));
	}
	
	public static int searchInsert(int[] A, int target) {
		
		for (int i=0;i<A.length;i++) {
			if (A[i] == target) {
				return i;
			}
			if (i+1 == A.length && A[i] < target) {
				return A.length;
			}
			if (A[i]<target && A[i+1]>target) {
				return i+1;
			}
		}
		
        return 0;
    }
}

  

posted @ 2019-07-30 17:38  gentleKay  阅读(101)  评论(0)    收藏  举报