zoukankan      html  css  js  c++  java
  • [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.

    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 1:

    Input: [1,3,5,6], 0
    Output: 0

    思路:

    搜索插入的位置。可遍历数组,target小于等于数组中的位置时,输出该数的坐标。进阶可用二分查找。重点是为什么返回的是lo,而不是mid呢?
    终止前一步为: low=high,得mid = low,此时如果target <= nums[mid],则high会改变,而low指向当前元素,即为满足要求的元素。
    如果target > nums[mid],则low会改变,而low指向mid下一个元素。
    如果key大于数组最后一个元素,low最后变为nums.size(),即没有元素大于key,返回 nums.size()。

     1 public class Solution35 {
     2     public int searchInsert(int[] nums, int target) {
     3         /*遍历方法:
     4         for(int i = 0; i < nums.length;i++){
     5             if(target<=nums[i]){
     6                 return i;
     7             }            
     8         } 
     9         return nums.length;*/
    10         int lo = 0;
    11         int hi = nums.length-1;
    12         int mid = 0;
    13         while(lo<=hi){
    14             mid = lo + (hi - lo)/2;
    15             if(target <= nums[mid]) hi = mid-1;
    16             else lo = mid +1;
    17         }
    18         return lo;
    19         
    20     }
    21     public static void main(String[] args) {
    22         // TODO Auto-generated method stub
    23         int[] nums = {1,3,5,6};
    24         int target = 7;
    25         Solution35 solution35 = new Solution35();
    26         System.out.println(solution35.searchInsert(nums, target));
    27     }
    28 
    29 }
  • 相关阅读:
    Python——一个简单的类的创建和应用
    Python——Python+Pydev出现SyntaxError: Non-UTF-8 code
    Python——使用第三方库Pillow生成图片缩略图
    Excel——使用INDEX和SMALL实现条件筛选
    关与node-gpy
    云开发-web应用中使用数据库
    分享阿里的技术
    解决docker中apt-get不管用
    算法-二分查找与树的增删改查
    云开发(小程序端,web端+博客搭建部署)
  • 原文地址:https://www.cnblogs.com/zlz099/p/8144952.html
Copyright © 2011-2022 走看看