๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Search Insert Position

by dkswnkk 2021. 11. 9.

๋ฌธ์ œ

 

Search Insert Position - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฝ”๋“œ

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๋ฅผ ์ด์šฉํ•˜์—ฌ ํ•ด๊ฒฐํ–ˆ์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€