Loading

LeetCode记录之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

给定一个排序的数组和一个目标值,如果找到目标,返回索引。 如果没有,如果按顺序插入索引,返回索引。

您可以假定阵列中没有重复项。

以下是几个例子。
[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 class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         int k=0;
 4         if(target>nums[nums.length-1])
 5             return nums.length;
 6         if(target<nums[0])
 7             return 0;
 8         else{
 9             for(int i=0;i<nums.length-1;i++){
10                 if(nums[i]==target&&target<nums[i+1]){
11                     k=i;
12                     break;
13                 }
14                 if(nums[i]<target&&target<=nums[i+1]){
15                     k=i+1;
16                     break;
17                 }
18             }
19         }
20         return k;
21     }
22 }

 

posted @ 2017-09-07 14:14  xpang0  阅读(245)  评论(0编辑  收藏  举报