`
zhang_xzhi_xjtu
  • 浏览: 536790 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode] SearchforaRange

阅读更多
        public int[] searchRange(int[] A, int target) {

            if (A == null || A.length == 0) {
                return new int[] { -1, -1 };
            }
            int start = start(A, target);
            if (start == -1) {
                return new int[] { -1, -1 };
            }

            int end = end(A, start, A.length - 1, target);
            return new int[] { start, end };
        }

        private int start(int A[], int target) {
            int start = 0;
            int end = A.length - 1;
            while (start <= end) {
                if (start == end && A[start] == target) {
                    return start;
                }

                int mid = (start + end) / 2;
                if (A[mid] > target) {
                    end = mid - 1;
                    continue;
                }
                if (A[mid] < target) {
                    start = mid + 1;
                    continue;
                }
                end = mid;
            }

            return -1;
        }

        private int end(int A[], int start, int end, int target) {
            while (true) {
                if (start == end) {
                    return start;
                }
                int mid = (start + end + 1) / 2;
                if (A[mid] > target) {
                    end = mid - 1;
                    continue;
                }
                start = mid;
            }
        }
2
5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics