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;
            }
        }
  • 相关阅读:
    final、static关键字
    this关键字与super关键字区别
    JAVA常见报错
    Java抽象类和多态
    Java 类和接口的继承
    JAVA封装
    库存管理案例
    Map的遍历
    LinkedList vector集合,Set接口
    Collection,迭代器iterator,list接口
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7846209.html
Copyright © 2011-2022 走看看