leetcode [#35]

目录

题目

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.

Example:
[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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
public int searchInsert(int[] nums, int target) {
int N = nums.length;
int result = 0;
if(N == 0) return result;

for(int i = 0; i < N; i++){
if(nums[i] == target){
result = i;
break;
} else if(nums[i] > target) {
if(i == 0){
result = 0;
break;
} else {
result = i;
break;
}
} else {
if(i == N - 1){
result = N;
break;
}
}
}
return result;
}
}

注意事项

  1. 遍历数组,如果找到,返回下标;否则,一律在当前元素大于target的情况下确定插入位置,如果当前元素小于target则继续向后判断,但要注意是否到了末尾。