๋ฌธ์
์ฝ๋
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int start = 0;
int end = nums.size();
int ans = 0;
sort(nums.begin(),nums.end());
while(start<=end){
int mid = (start+end)/2;
if(mid>=nums.size()) break;
if(target == nums[mid]){
ans = mid;
break;
}
else if(target>nums[mid]){
if(mid+1<nums.size()){
if(target<nums[mid+1]){
ans = mid+1;
break;
}
}
start = mid+1;
}
else{
if(mid-1>=0){
if(target>nums[mid-1]){
ans = mid;
break;
}
}
end = mid-1;
}
}
if(target>nums.back()&&ans==0) ans = nums.size();
else if(target>nums.front()&&ans==0) ans = 1;
return ans;
}
};
ํ์ด
๋ฌธ์ ์์ o(log n) ์๊ฐ ๋ณต์ก๋๋ฅผ ์๊ตฌํ๊ธฐ ๋๋ฌธ์, binary search๋ฅผ ์ด์ฉํ์ฌ ํด๊ฒฐํ์ต๋๋ค.
'Algorithm ๐ง๐ปโ๐ป > Leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Leetcode,c++] Maximum Subarray (0) | 2021.11.09 |
---|---|
[Leetcode,c++] Valid Parentheses (0) | 2021.11.09 |
[Leetcode,c++] Palindrome Number (0) | 2021.11.09 |
[Leetcode,c++] Find the City With the Smallest Number of Neighbors at a Threshold Distance (0) | 2021.11.07 |
[Leetcode,c++] Combination Sum (0) | 2021.11.07 |
[Leetcode,c++] Multiply-Strings (0) | 2021.11.07 |
๋๊ธ