鎼滅储鎻掑叆浣嶇疆
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了鎼滅储鎻掑叆浣嶇疆相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e6%8f%92%e5%85%a5' title='鎻掑叆'>鎻掑叆
tar image 鎺掑簭 娌℃湁 break res sea 鐩爣LC 鎼滅储鎻掑叆浣嶇疆
缁欏畾涓€涓帓搴忔暟缁勫拰涓€涓洰鏍囧€硷紝鍦ㄦ暟缁勪腑鎵惧埌鐩爣鍊硷紝骞惰繑鍥炲叾绱㈠紩銆傚鏋滅洰鏍囧€间笉瀛樺湪浜庢暟缁勪腑锛岃繑鍥炲畠灏嗕細琚寜椤哄簭鎻掑叆鐨勪綅缃€?/p>
浣犲彲浠ュ亣璁炬暟缁勪腑鏃犻噸澶嶅厓绱犮€?/p>
绀轰緥 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
鑷繁鎯崇殑棰樿В锛氬畬鍏ㄦ槸鏆村姏姹傝В
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int result = -1;
//姝e父鏌ユ壘鍒扮殑鎯呭喌
for (int i = 0; i < nums.size(); i++)
{
if (target == nums[i])
{
result = i;
break;
}
}
//娌℃湁鏌ユ壘鍒扮殑鎯呭喌
if (result == -1)
{
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] > target)
{
result = i;
break;
}
}
//target鍊兼瘮鏁扮粍涓墍鏈夊€奸兘瑕佸ぇ鐨勬儏鍐? if (result == -1)
{
result = nums.size();
}
}
return result;
}
};
鏃堕棿澶嶆潅搴︼細O锛圢锛?/p>
绌洪棿澶嶆潅搴︼細O锛?锛?/p>
杩愯鎯呭喌濡備笅锛氾紙澶彍浜嗘垜锛?/p>
浣跨敤浜屽垎鏌ユ壘锛?/p>
//浜屽垎鏌ユ壘娉?class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int Left = 0;//鏁扮粍鏈€宸︾绱㈠紩
int Right = nums.size() - 1;//鏁扮粍鏈€鍙崇绱㈠紩
int mid = 0;
while (Left <= Right)
{
//mid = (Left + Right) / 2;
//鍙互闃叉鏁扮粍涓婃孩鍑? mid = Left + (Right - Left)/2;
if (nums[mid] == target)
{
return mid;
}
else if (target > nums[mid])
{
Left = mid + 1;
}
else
{
Right = mid - 1;
}
}
return Left;
}
};
鏃堕棿澶嶆潅搴︼細O锛坙ogN)
绌洪棿澶嶆潅搴︼細O锛圢锛?/p>
杩愯鎯呭喌锛?/p>
以上是关于鎼滅储鎻掑叆浣嶇疆的主要内容,如果未能解决你的问题,请参考以下文章
Zotero锝滃鐢≒ubMed鎼滅储寮曟搸锛屾煡鎵剧浉鍏虫枃鐚紒