题干

LeetCode-34-在排序数组中查找元素的第一个和最后一个位置
image.png

讲解

排序数组找一个值,自然而然就能想到二分查找;当然如果是直接循环也没问题,只不过时间复杂度是O(n),不符合题干要求;
题干中我们可以看到他要求O(log n)的时间复杂度,所以用的方法就是二分查找;

这里分享一下y总的整数二分查找的模板
image.png
注意第二种方法是 (l+r+1)/2

题解

  1. public static int[] searchRange(int[] nums, int target) {
  2. if(nums.length == 0){
  3. return new int[]{-1,-1};
  4. }
  5. int left = check_left(nums, target);
  6. int right = check_right(nums, target);
  7. if(nums[left] != target){
  8. return new int[]{-1, -1};
  9. }else{
  10. return new int[]{left, right};
  11. }
  12. }
  13. /**
  14. * 查找第一个出现的位置
  15. * @param nums
  16. * @param target
  17. * @return
  18. */
  19. public static int check_left(int[] nums, int target){
  20. int left = 0;
  21. int right = nums.length-1;
  22. while(left < right){
  23. int temp = (left+right)/2;
  24. if(nums[temp]>=target){
  25. right = temp;
  26. }else{
  27. left = temp+1;
  28. }
  29. }
  30. return left;
  31. }
  32. /**
  33. * 查找最后一个出现的位置
  34. * @param nums
  35. * @param target
  36. * @return
  37. */
  38. public static int check_right(int[] nums, int target){
  39. int left = 0;
  40. int right = nums.length-1;
  41. while(left < right){
  42. int temp = (left+right+1)/2;
  43. if(nums[temp]<=target){
  44. left = temp;
  45. }else{
  46. right = temp-1;
  47. }
  48. }
  49. return left;
  50. }