在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

[LintCode/LeetCode] Search for a Range [左右边界法/一次循环法]

2016-8-16 12:48| 发布者: zhangjf| 查看: 764| 评论: 0

摘要: Problem Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not found in the array, return . Example Given and target value 8,return . ...
Problem

Given a sorted array of n integers, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1].

Example

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Challenge

O(log n) time.

Note

首先,建立二元结果数组res,起点start,终点end。
二分法求左边界:
当中点小于target,start移向中点,否则end移向中点;
先判断起点,再判断终点是否等于target,如果是,赋值给res[0]。
二分法求右边界:
当中点大于target,end移向中点,否则start移向中点;
先判断终点,再判断起点是否等于target,如果是,赋值给res[1]。
返回res。

Solution
  1. public class Solution {
  2. public int[] searchRange(int[] A, int target) {
  3. int []res = {-1, -1};
  4. if (A == null || A.length == 0) return res;
  5. int start = 0, end = A.length - 1;
  6. int mid;
  7. while (start + 1 < end) {
  8. mid = start + (end - start) / 2;
  9. if (A[mid] < target) start = mid;
  10. else end = mid;
  11. }
  12. if (A[start] == target) res[0] = start;
  13. else if (A[end] == target) res[0] = end;
  14. else return res;
  15. start = 0;
  16. end = A.length - 1;
  17. while (start + 1 < end) {
  18. mid = start + (end - start) / 2;
  19. if (A[mid] > target) end = mid;
  20. else start = mid;
  21. }
  22. if (A[end] == target) res[1] = end;
  23. else if (A[start] == target) res[1] = start;
  24. else return res;
  25. return res;
  26. }
  27. }
复制代码
Another Binary Search Method
  1. public class Solution {
  2. public int[] searchRange(int[] nums, int target) {
  3. int n = nums.length;
  4. int[] res = {-1, -1};
  5. int start = 0, end = n-1;
  6. while (nums[start] < nums[end]) {
  7. int mid = start + (end - start) / 2;
  8. if (nums[mid] > target) end = mid - 1;
  9. else if (nums[mid] < target) start = mid + 1;
  10. else {
  11. if (nums[start] < target) start++;
  12. if (nums[end] > target) end--;
  13. }
  14. }
  15. if (nums[start] == target) {
  16. res[0] = start;
  17. res[1] = end;
  18. }
  19. return res;
  20. }
  21. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 15:50

Copyright 2015-2025 djqfx

返回顶部