zoukankan      html  css  js  c++  java
  • 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.
    -----------------------
    Input: [1,3,5,6], 5
    Output: 2
    -----------------------
    Input: [1,3,5,6], 2
    Output: 1
    -----------------------
    Input: [1,3,5,6], 7
    Output: 4
    -----------------------
    Input: [1,3,5,6], 0
    Output: 0

     ------------------------------------------------------------------------------------------------------------------------

    返回target在有序数组中的位置。如果没有找到,就返回这个数应该放在的位置:

     代码如下:

    int searchInsert(vector<int>& nums, int target) {
            if(nums.capacity() == 0) 
                return 0;
            if(target > nums[nums.capacity() - 1])     //如果要找的数比最后一个数还要大,它的位置应该在末尾
                return nums.capacity(); 
            for(int i = 0; i < nums.capacity(); i++){ 
                if(nums[i] >= target)                  //找到这个数,或者把它放在第一个比它大的数的位置
                    return i;
            }
        }
  • 相关阅读:
    压缩感知的由来
    VS2010自动崩溃问题
    随机过程好书推荐
    Kernel PCA
    稀疏性与L1范数
    豆瓣关于计算机视觉的书评及介绍
    压缩感知测量矩阵的研究现状(转)
    信号的功率谱、能量谱、频谱的区别(转)
    vc++ & matlab 换行符号
    arg min 的含义
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7846209.html
Copyright © 2011-2022 走看看