[LC]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.

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

②中文题目

   

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 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

③ 思路

    这就是个遍历查找判决过程,相等就输出当前索引。但是要注意边界问题,

      1、target<nums[0]时,输出索引是0.

      2、target>nums[nums.length]时,输出索引为nums.length。

      3、有一个地方要特别注意,第8行代码,如果不先保证i+1<nums.length,那么nums[i+1]会越界。

④代码

  

 1 class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3       int k = Integer.MIN_VALUE;
 4         //int k = Integer.MIN_VALUE;
 5         for(int i=0;i<nums.length;i++){
 6               if(nums[i]==target)
 7                      k=i;
 8               if(i+1<nums.length&&nums[i]<target&&nums[i+1]>target)
 9                      k=i+1;       
10        }
11       if(nums[0]>target)
12                      k=0;
13       if(nums[nums.length-1]<target)
14                      k=nums.length;
15       return k;
16     }
17 }

⑤今天我

Runtime: 0 ms, faster than 100.00% of Java online submissions for Search Insert Position.
Memory Usage: 38.8 MB, less than 100.00% of Java online submissions for Search Insert Position.

耗时0ms,击败了100%的用java的人,尽管这个程序很简单,但是还是很高兴。该午休了,下午去实验室。

猜你喜欢

转载自www.cnblogs.com/zf007/p/11526729.html