zoukankan      html  css  js  c++  java
  • [array] leetcode

    leetcode - 35. Search Insert Position - Easy

    descrition

    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
    
    

    解析

    二分查找的实现。

    code

    
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class Solution{
    public:
    	int searchInsert(vector<int>& nums, int target){
    		int ileft = 0, iright = nums.size() - 1;
    		while(ileft <= iright){
    			int imid = ileft + (iright - ileft) / 2;
    			if(nums[imid] == target)
    				return imid;
    			else if (nums[imid] < target){
    				ileft = imid + 1;
    			}else{
    				// nums[imid] > target
    				iright = imid - 1;
    			}
    		}
    
    		return ileft;
    	}
    };
    
    int main()
    {
    	return 0;
    }
    
  • 相关阅读:
    php高效率写法
    php经典bug
    cideogniter部署到阿里云服务器出现session加载错误
    linux gcc编译protocol
    linux权限问题
    http协议详解
    哈希表
    c语言函数
    socket相关函数
    构建之法阅读笔记05
  • 原文地址:https://www.cnblogs.com/fanling999/p/7841621.html
Copyright © 2011-2022 走看看