LeetCode_Study_Plan/Algorithm

35. Search Insert Position java

개발하는루루 2022. 12. 20. 18:16

https://leetcode.com/problems/search-insert-position/?envType=study-plan&id=algorithm-i 

 

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(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        int ans = 0;

        if (nums[nums.length-1] < target) {
            return nums.length;
        } else if (nums[0] > target) {
            return 0;
        }
        
        while (start <= end) {
            int mid = (start + end)/2;
            System.out.println("start: " + start + " mid: " + mid + " end: " + end);

            if (nums[mid] < target) {
                start = mid + 1;
                ans = start;
            } else if (nums[mid] == target) {
                ans = mid;
                break;
            }
            else {
                end = mid - 1;
                ans = mid;
            }
        }

        return ans;
    }
}