Post

[LeetCode 35] Search Insert Position

LeetCode 35 (Java)
[Search Insert Position] 문제 풀이

[LeetCode 35] Search Insert Position

문제 바로가기


Description


Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.


Example 1


  • Input: nums = [1,3,5,6], target = 5
  • Output: 2


Example 2


  • Input: nums = [1,3,5,6], target = 2
  • Output: 1


Example 3


  • Input: nums = [1,3,5,6], target = 7
  • Output: 4


Constraints


  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order.
  • -10^4 <= target <= 10^4







Code


내 제출


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public int searchInsert(int[] nums, int target) {
        int result = 0;
        int numsLength = nums.length;

        while (result < numsLength) {
            int mid = (result + numsLength) >>> 1; // 안전한 중간 값 연산을 위해 비트연산을 사용
            if (nums[mid] >= target) {
                numsLength = mid;
            } else {
                result = mid + 1;
            }
        }
        //bw.write(String.valueOf(result));
        return result;
    }
}


RuntimeMemory
0 ms43.1 MB


다른 풀이


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public int searchInsert(int[] nums, int target) {
        int low =0;
        int high = nums.length-1;
        while(low<= high){
            int mid = (low+ high)/2;
            if(nums[mid]== target){
                return mid;
            }else if( nums[mid]>target){
                high = mid-1;
            }else{
                low= mid+1;
            }
        }
        return low;
    }
}


Reference


  • https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0035.Search%20Insert%20Position/Solution.java
This post is licensed under CC BY 4.0 by the author.