예제 #1
0
        /// <summary>
        /// 查找峰顶索引
        /// </summary>
        /// <param name="mountainArr"></param>
        /// <returns></returns>
        private int PeakIndexInMountainArray(MountainArray A)
        {
            int left = 0, right = A.Length() - 1;
            int mid = 0;

            while (left <= right)
            {
                mid = left + ((right - left) >> 1);
                if (mid == 0)
                {
                    if (A.Get(mid) < A.Get(mid + 1))
                    {
                        return(mid + 1);
                    }
                    else
                    {
                        return(mid);
                    }
                }
                else if (mid == A.Length() - 1)
                {
                    if (A.Get(mid - 1) > A.Get(mid))
                    {
                        return(mid - 1);
                    }
                    else
                    {
                        return(mid);
                    }
                }
                else if (A.Get(mid - 1) < A.Get(mid) && A.Get(mid) < A.Get(mid + 1))
                {
                    left = mid + 1;
                }
                else if (A.Get(mid - 1) > A.Get(mid) && A.Get(mid) > A.Get(mid + 1))
                {
                    right = mid - 1;
                }
                else
                {
                    return(mid);
                }
            }
            return(-1);
        }
예제 #2
0
        /// <summary>
        /// 1095. 山脉数组中查找目标值
        /// </summary>
        /// <param name="target"></param>
        /// <param name="mountainArr"></param>
        /// <returns></returns>
        public int FindInMountainArray(int target, MountainArray mountainArr)
        {
            int peakIndex = PeakIndexInMountainArray(mountainArr);

            if (target > mountainArr.Get(peakIndex))
            {
                return(-1);
            }

            int minLeft = BinarySearchLeft(target, peakIndex, mountainArr);

            if (minLeft != -1)
            {
                return(minLeft);
            }

            int minRight = BinarySearchRight(target, peakIndex + 1, mountainArr);

            return(minRight);
        }
예제 #3
0
        private int BinarySearchRight(int target, int low, MountainArray mountainArr)
        {
            int left = low, right = mountainArr.Length() - 1, mid = 0;
            int min = -1;

            while (left <= right)
            {
                mid = left + ((right - left) >> 1);
                if (mountainArr.Get(mid) < target)
                {
                    right = mid - 1;
                }
                else if (mountainArr.Get(mid) > target)
                {
                    left = mid + 1;
                }
                else
                {
                    min   = mid;
                    right = mid - 1;
                }
            }
            return(min);
        }