您的位置:首页 > 其它

[leetcode-查找]--35. Search Insert Position

2017-02-08 16:01 531 查看
Question 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

中文: 给定一个有序数组和目标值target。如果target在数组中就返回索引,如果不在就返回插入位置的索引。

这题一看就比较简单,直接一轮遍历就可以解决:

public static int searchInsert(int[] nums, int target) {

for(int i=0; i<nums.length; i++){

//找到就直接返回index
if(nums[i] == target ){
return i;
}

if(nums[i] < target && i< (nums.length-1) && nums[i+1] > target){
return i+1;
}

if(nums[i] < target && i==(nums.length-1)){
return nums.length;
}
}

//当nums[0]都比target大时
return 0;
}


测试案例:

public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4, 7, 8, 9, 12, 22, 65};
System.out.print( Question35.searchInsert(arr, 44)) ;
}


输出:

10


本文完整源码github:

https://github.com/leetcode-hust/leetcode/blob/master/louyuting/src/leetcode/Question35.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode