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

    要完成的函数:

    int searchInsert(vector<int>& nums, int target) 

     代码:

    int searchInsert(vector<int>& nums, int target) 
        {
    	    if(nums.empty())
    	    return 0;//判断是否为空
    	    else
    	    {
                    for(int i=0;i<nums.size();i++)
    		{
    		    if(target==nums[i])
    		    return i;//如果直接能找到就返回
    		    else if(target<nums[i])
    		    return i;//如果不能找到但是找到一个比它大的数,再加上这是一个升序排列的vector,所以这里可以这样处理,会快上很多
    		}
    	    return nums.size();//如果跑完一遍都没找到等于target的数,也没找到比它大的,那么它只能在最后一位
    	    }
        }
    

    说明:

    1、这道题目如果按照常规思路,先for循环跑一遍确认target在不在vector里面,如果在就返回index(位置),如果不在,再跑一遍for循环找到第一个比target大的数值,然后输出index。这样会慢上很多。我们不如直接在一个for循环里面搞定。

    2、其实这是一道二分查找的题目,二分查找的算法去做会比我的从头到尾遍历一遍的暴力做法更省时间。但可能是因为测试集数据量太小的原因,我找了一个discussion里面的二分查找,跑出来反而比暴力解法慢了。如下:

    int searchInsert(vector<int>& nums, int target) {
            int low = 0, high = nums.size()-1;
            while (low <= high) {
                int mid = low + (high-low)/2;
                if (nums[mid] < target)
                    low = mid+1;
                else
                    high = mid-1;
            }
            return low;
        }

    这份代码属于leetcode上的用户a0806449540,感谢分享。侵删。

     

  • 相关阅读:
    Java 下载网络资源
    Java11 ThreadLocal的remove()方法源码分析
    软件测试的术语SRS,HLD,LLD,BD,FD,DD意义
    2020年12月2日
    20201129
    2020年11月28日
    程序员的三门课
    中间件到底是个什么鬼东西?
    接口测试框架的形成过程
    一个字符到底等于多少字节
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8709318.html
Copyright © 2011-2022 走看看