https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

 

Find First and Last Position of Element in Sorted Array - LeetCode

Can you solve this real interview question? Find First and Last Position of Element in Sorted Array - Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in t

leetcode.com

 

이진탐색 두번 시행

1. 시작지점 찾기

2. 끝나는 지점 찾기

 

class Solution {
    public int[] searchRange(int[] nums, int target) {

        int start = -1;
        int end = -1;

        int left = 0;
        int right = nums.length - 1;
        // start 위치 찾기
        while (left <= right) {

            int mid = (left + right) / 2;

            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
            if (nums[mid] == target) {
                start = mid;
            }
        }

        //end 위치 찾기

        left = 0;
        right = nums.length - 1;
        while (left <= right) {

            int mid = (left + right) / 2;

            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
            if (nums[mid] == target) {
                end = mid;
            }
        }

        return new int[]{start, end};
    }
}

+ Recent posts