• LeetCode: Search for a Range


    一次过

     1 class Solution {
     2 public:
     3     vector<int> searchRange(int A[], int n, int target) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int left = 0;
     7         int right = n-1;
     8         while (left <= right) {
     9             int mid = (left+right)/2;
    10             if (target == A[mid]) {
    11                 int l, r;
    12                 l = r = 0;
    13                 while (A[mid] == A[mid-l]) l++;
    14                 while (A[mid] == A[mid+r]) r++;
    15                 vector<int> ret;
    16                 ret.push_back(mid-l+1);
    17                 ret.push_back(mid+r-1);
    18                 return ret;
    19             }
    20             if (target > A[mid]) left = mid+1;
    21             else right = mid-1;
    22         }
    23         return {-1, -1};
    24     }
    25 };

     C#

     1 public class Solution {
     2     public int[] SearchRange(int[] nums, int target) {
     3         int left = 0;
     4         int right = nums.Length - 1;
     5         int[] ans = new int[2];
     6         while (left <= right) {
     7             int mid = (left + right) / 2;
     8             if (target == nums[mid]) {
     9                 int l = 0, r = 0;
    10                 while (mid - l >= 0 && nums[mid] == nums[mid-l]) l++;
    11                 while (mid + r < nums.Length && nums[mid] == nums[mid+r]) r++;
    12                 ans[0] = mid - l + 1;
    13                 ans[1] = mid + r - 1;
    14                 return ans;
    15             }
    16             if (target > nums[mid]) left = mid + 1;
    17             else right = mid - 1;
    18         }
    19         ans[0] = ans[1] = -1;
    20         return ans;
    21     }
    22 }
    View Code
  • 相关阅读:
    二叉排序树 常用函数小结
    二叉树的应用:二叉排序树的删除
    剑指 Offer 32
    剑指 Offer 32
    剑指 Offer 68
    剑指 Offer 28. 对称的二叉树 做题小结
    正则表达式不要背
    剑指 Offer 55
    LeetCode226. 翻转二叉树 做题小结
    Tools | 编程IED/编译器
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3032786.html
Copyright © 2020-2023  润新知