题目出处:https://leetcode.com/problems/search-insert-position/
题目描述:
给定排序数组和目标值,如果找到目标,则返回索引。 如果没有,请返回索引按顺序插入的索引。
您可以假设数组中没有重复项。
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
代码:
var searchInsert = function(nums, target) {
//假设它在数组中
var i =0;
var len = nums.length;
while(i<len){
if(nums[i] == target){
return i
}else{
i++
}
};
//它不在数组中
if(i ==len){
var j =0;
while(nums[j]<target){
j++
};
}
return j
};
笔记:
感觉写过几次就能很自然的写出来,不过没有使用for循环。总有一种很古老的感觉