본문 바로가기

Programing/Algorithm

[LeetCode] 34. Find First and Last Position of Element in Sorted Array

728x90

 

 

 

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

 

public class Solution
{
    public int[] SearchRange(int[] nums, int target)
    {
        return new int[] { GetStartIndex(nums, target), GetEndIndex(nums, target) };
    }

    private int GetStartIndex(int[] nums, int target)
    {
        int start = 0;
        int end = nums.Length - 1;

        int startIndex = -1;

        while (start <= end)
        {
            int pivot = (start + end) / 2;

            if (nums[pivot] < target)
            {
                start = pivot + 1;
            }
            else if (nums[pivot] > target)
            {
                end = pivot - 1;
            }
            else
            {
                startIndex = pivot;
                end = pivot - 1;
            }
        }

        return startIndex;
    }

    private int GetEndIndex(int[] nums, int target)
    {
        int start = 0;
        int end = nums.Length - 1;

        int endIndex = -1;

        while (start <= end)
        {
            int pivot = (start + end) / 2;

            if (nums[pivot] < target)
            {
                start = pivot + 1;
            }
            else if (nums[pivot] > target)
            {
                end = pivot - 1;
            }
            else
            {
                endIndex = pivot;
                start = pivot + 1;
            }
        }

        return endIndex;
    }
}

 

 

 

728x90