Search Insert Position


  • 0
    P
    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
        	if(nums.size() < 1)
        		return 0;
        	else
        	{
        		int m;
        		int start = 0;
        		int end = nums.size();
        
        		while(end > start)
        		{
        			m = (end+start)/2;
        
        			if(nums[m] == target)
        				return m;
        			else if(nums[m] < target)
        			{
        				if(m + 1< nums.size() && nums[m+1] > target)
        					return (m+1);
        				start = m + 1;
        			}
        			else
        			{
        				if( m > 0 && nums[m-1] < target)
        					return m;
        				end = m;
        			}
        		}
        		if(start == 0)
        			return 0;
        		else if(start == nums.size())
        			return nums.size();
        		else
        		{
        			if(nums[start] == target)
        				return start;
        			else if(nums[start] < target)
        				return (start+1);
        			else
        				return start;	
        		}
        	}
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.