34. 在排序数组中查找元素的第一个和最后一个位置

public class 二分查找
    {
        public int[] GetSS(int[] nums, int target)
        {
            if (nums.Length == 0)
            {
                return new int[] { -1, -1 };
            }
            var fristIndex = GetFristIndex(nums, target);
            if (fristIndex == -1)
            {
                return new int[] { -1, -1 };
            }
            var secondIndex = GetSecondIndex(nums, target);
            return new int[] { fristIndex, secondIndex };
        }

        private int GetSecondIndex(int[] nums, int target)
        {
            int left = 0;
            int right = nums.Length - 1;
            while (left < right)
            {
                var avg = left + (right - left + 1) / 2;
                if (nums[avg] < target)
                {
                    // 此时target在[avg+1, right]
                    left = avg + 1;
                }
                else if (nums[avg] == target)
                {
                    // 此时 target在[avg, right]
                    left = avg;
                }
                else
                {
                    // nums[avg] > target
                    // target在[left,avg - 1]
                    right = avg - 1;
                }
            }
            if (nums[left] == target)
            {
                return left;
            }
            else
            {
                return -1;
            }
        }

        private int GetFristIndex(int[] nums, int target)
        {
            int left = 0;
            int right = nums.Length - 1;
            while (left < right)
            {
                var avg = left + (right - left) / 2;
                if (nums[avg] < target)
                {
                    // 此时target在[avg+1, right]
                    left = avg + 1;
                }
                else if (nums[avg] == target)
                {
                    // 此时 target在[left, avg]
                    right = avg;
                }
                else
                {
                    // nums[avg] > target
                    // target在[left,avg - 1]
                    right = avg - 1;
                }
            }
            if (nums[left] == target)
            {
                return left;
            }
            else
            {
                return -1;
            }
        }

    }

自己确实很菜,数据机构,算法,

posted @ 2022-07-20 22:33  vba是最好的语言  阅读(37)  评论(0编辑  收藏  举报