【LeetCode题解】Search Insert Position

Search Insert Position

 (Java代码)

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 class Solution {
	public int searchInsert(int[] A, int target) {
		int result = 0;
		if (target < A[0]) {
			result = 0;
		}
		if (target > A[A.length - 1]) {
			result = A.length;
		}
		for (int i = 0; i < A.length; i++) {
			if (target == A[i]) {
				result = i;
			}
			if (i != A.length - 1) {
				if ((target > A[i]) && target < A[i + 1]) {
					result = i + 1;
				}
			}

		}
		return result;

	}
}

解题思路:这道题不难我就是先看在不在数组里,在的话输出i,不在的话看是不是比前一个大,比后一个小,注意数组越界的问题。

要是上来就比第一个数小就输出零,比最后一个大输出数组长度。

你可能感兴趣的:(java,LeetCode,search,insert,Positi)