34. Search for a Range

题目:Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

思路:利用双指针,前指针从头,后指针从尾开始向之间搜索。

public static int[] searchRange(int[] nums, int target) {
          int[] result={-1,-1};
          int starting=0;
          int ending=nums.length-1;
          while(starting<=ending)
          {
              if(nums[starting]==target)
              {
                  result[0]=starting;
              }
              else{
                  starting++;
              }
              if(nums[ending]==target)
              {
                  result[1]=ending;
              }
              else
              {
                  ending--;
              }
              if(result[0]!=-1&&result[1]!=-1)
              {
                  break;
              }
          }
          return result;
    }

Accepted后发现才击败12.7%Java提交。醉了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容