国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

leecode 解題總結(jié):35. Search Insert Position

2019-11-10 19:07:59
字體:
供稿:網(wǎng)友
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*問題: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.Here are few examples.[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7 → 4[1,3,5,6], 0 → 0分析:這是二分查找的lowwer_bound的問題。輸入:4 51 3 5 64 21 3 5 64 71 3 5 64 01 3 5 6輸出2140關鍵:1 lowwer_bound:		//low == high時,如果找到,就返回		if(nums.at(low) >= target)		{			return low;		}		//說明是數(shù)組最后一個元素,返回low+1		else		{			return low + 1;		}*/class Solution {public:	int lower_bound(vector<int>& nums , int target)	{		if(nums.empty())		{			return -1;		}		int low = 0;		int high = nums.size() - 1;		int mid;		while(low < high)		{			mid  = low + (high - low) / 2;			//中間大于目標值,目標值,mid可能是結(jié)果,繼續(xù)在左半部分尋找			if(nums.at(mid) >= target)			{				high = mid;			}			//中間值 < 目標值,mid不可能是結(jié)果,在右半部分尋找			else			{				low = mid + 1;			}		}		//low == high時,如果找到,就返回		if(nums.at(low) >= target)		{			return low;		}		//說明是數(shù)組最后一個元素,返回low+1		else		{			return low + 1;		}	}    int searchInsert(vector<int>& nums, int target) {		int high = lower_bound(nums , target);		return high;    }};void PRocess(){	int num ;	int value;	vector<int> nums;	int target;	Solution solution;	vector<int> results;	while(cin >> num >> target)	{		nums.clear();		for(int i  = 0 ; i < num ; i++)		{			cin >> value;			nums.push_back(value);		}		int result = solution.searchInsert(nums , target);		cout << result << endl;	}}int main(int argc , char* argv[]){	process();	getchar();	return 0;}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 乌兰浩特市| 安乡县| 疏附县| 连平县| 黔江区| 龙口市| 瓮安县| 宁南县| 桂阳县| 藁城市| 大渡口区| 古浪县| 汝州市| 耒阳市| 北海市| 永州市| 武冈市| 东台市| 建湖县| 东乌珠穆沁旗| 湖北省| 昆山市| 奇台县| 即墨市| 西吉县| 定南县| 临安市| 额尔古纳市| 寿光市| 济阳县| 潜江市| 盈江县| 麦盖提县| 怀安县| SHOW| 玛曲县| 淮南市| 雷州市| 阿坝县| 仁布县| 沙湾县|