題目描述
給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。
你可以假設數組中無重複元素。
示例 1:
輸入: [1,3,5,6], 5
輸出: 2
示例 2:
輸入: [1,3,5,6], 2
輸出: 1
示例 3:
輸入: [1,3,5,6], 7
輸出: 4
示例 4:
輸入: [1,3,5,6], 0
輸出: 0
解決方案
class Solution {
public int searchInsert(int[] nums, int target) {
if (nums[nums.length-1]<target){
return nums.length;
}
for (int i = 0; i <nums.length ; i++) {
if (target<=nums[i]){
return i;
}
}
return 0;
}
}