zoukankan      html  css  js  c++  java
  • 035 Search Insert Position 搜索插入位置

    给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
    你可以假设在数组中无重复元素。
    案例 1:
    输入: [1,3,5,6], 5
    输出: 2
    案例 2:
    输入: [1,3,5,6], 2
    输出: 1
    案例 3:
    输入: [1,3,5,6], 7
    输出: 4
    案例 4:
    输入: [1,3,5,6], 0
    输出: 0
    详见:https://leetcode.com/problems/search-insert-position/description/

    Java实现:

    class Solution {
        public int searchInsert(int[] nums, int target) {
            int size=nums.length;
            if(size==0||nums==null){
                return -1;
            }
            int l=0;
            int r=size-1;
            int m=0;
            while(l<=r){
                m=(l+r)>>1;
                if(nums[m]==target){
                    return m;
                }else if(nums[m]>target){
                    --r;
                }else{
                    ++l;
                }
            }
            return l;
        }
    }
    

     C++实现:

    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            int size=nums.size();
            if(size==0||nums.empty())
            {
                return -1;
            }
            int l=0,r=size-1,m=0;
            while(l<=r)
            {
                m=(l+r)>>1;
                if(nums[m]==target)
                {
                    return m;
                }
                else if(nums[m]>target)
                {
                    r=m-1;
                }
                else
                {
                    l=m+1;
                }
            }
            return l;
        }
    };
    
  • 相关阅读:
    Hadoop学习资料收集
    sed使用详解
    shell编程001
    电影《无法触碰》
    正则表达式
    I/O重定向与管道
    bash基础知识
    用户权限模型
    Linux文件管理常用命令
    根文件系统详解
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8688201.html
Copyright © 2011-2022 走看看