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;
            }
        }
  • 相关阅读:
    ecos启动流程分析
    ecos中断机制分析(2)
    Redboot修改实例
    6/6 项目开工
    6/8 可配置工作流 实现思路
    6/7 第2次碰头
    6/10 主要流程和界面讨论会确定
    6/10 设计方案目录草案
    C# 获取某月的第一天和最后一天
    【Manage It】之掌控项目
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7846209.html
Copyright © 2011-2022 走看看