當前位置:
首頁 >
LeetCode - 35. Search Insert Position
發布時間:2025/3/8
23
豆豆
生活随笔
收集整理的這篇文章主要介紹了
LeetCode - 35. Search Insert Position
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
35. Search Insert Position?
Problem's Link
?----------------------------------------------------------------------------
Mean:?
給定一個有序數組和一個數k,求k在這個數組中插入的下標.
analyse:
二分查找.
Time complexity: O(N)
?
view code
/*** -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights reserved.
* -----------------------------------------------------------------
* ? ? ? Author: crazyacking
* ? ? ? Date ?: 2016-03-02-08.49
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long(LL);
typedef unsigned long long(ULL);
const double eps(1e-8);
class Solution
{
public:
? ?int searchInsert(vector<int>& nums, int target)
? ?{
? ? ? ?int len=nums.size();
? ? ? ?if(len==0 || target<=nums[0])
? ? ? ? ? ?return 0;
? ? ? ?if(target>nums[len-1])
? ? ? ? ? ?return len;
? ? ? ?int low=0,high=len-1;
? ? ? ?while(low<=high)
? ? ? ?{
? ? ? ? ? ?int mid=(low+high)>>1;
? ? ? ? ? ?if(target<nums[mid])
? ? ? ? ? ?{
? ? ? ? ? ? ? ?if(mid-1>=0 && target>nums[mid-1])
? ? ? ? ? ? ? ? ? ?return mid;
? ? ? ? ? ? ? ?high=mid-1;
? ? ? ? ? ?}
? ? ? ? ? ?else if(target>nums[mid])
? ? ? ? ? ?{
? ? ? ? ? ? ? ?if(mid+1<len && target<nums[mid+1])
? ? ? ? ? ? ? ? ? ?return mid+1;
? ? ? ? ? ? ? ?low=mid+1;
? ? ? ? ? ?}
? ? ? ? ? ?else
? ? ? ? ? ? ? ?return mid;
? ? ? ?}
? ?}
};
int main()
{
? ?Solution solution;
? ?int n,k;
? ?while(cin>>n>>k)
? ?{
? ? ? ?vector<int> ve;
? ? ? ?for(int i=0;i<n;++i)
? ? ? ?{
? ? ? ? ? ?int tempVal;
? ? ? ? ? ?cin>>tempVal;
? ? ? ? ? ?ve.push_back(tempVal);
? ? ? ?}
? ? ? ?cout<<"pos="<<solution.searchInsert(ve,k)<<endl;
? ?}
? ?return 0;
}
/*
*/
轉載于:https://www.cnblogs.com/crazyacking/p/5233587.html
總結
以上是生活随笔為你收集整理的LeetCode - 35. Search Insert Position的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Grunt构建自动化开发环境
- 下一篇: System Center Techni