All Articles

34. Find First And Last Position Of Element In Sorted Array

Problem

34. Find First and Last Position of Element in Sorted Array

Left boundary

%0 First position of target = 8 cluster_step4 step4, return left cluster_step1 step1 cluster_step2 step2, left = mid + 1 cluster_step3 step3, right = mid - 1 nums1 5 7 7 8 8 10 indices1 left mid right indices1:left->nums1:5 indices1:mid->nums1:7_2 indices1:right->nums1:10 nums2 5 7 7 8 8 10 indices2 left mid right indices2:left->nums2:8_1 indices2:mid->nums2:8_2 indices2:right->nums2:10 nums3 5 7 7 8 8 10 indices3 left mid right indices3:left->nums3:8_1 indices3:mid->nums3:8_1 indices3:right->nums3:8_1 nums4 5 7 7 8 8 10 indices4 left mid right indices4:left->nums4:8_1 indices4:right->nums4:7_2
int findFirst(int[] nums, int target) {
   int left = 0, right = n - 1, mid = 0;
   while (left <= right) {
      mid = left + (right - left) / 2;

      if (nums[mid] == target) {
         // attention (1)
         right = mid - 1;
      } else if (nums[mid] > target) {
         right = mid - 1;
      } else if (nums[mid] < target) {
         lo = mid + 1;
      }
   }

   //attention (2)
   return left < n && nums[left] == target ? left: -1;
}

Attention

To find the first position of the target

  1. when one position is found, we need to move our search space to the left.
  2. After the loop finishes, we need to check
  • left is a valid index of the original array.
  • The element at left is equal to target.

Right boundary

%0 Last position of target = 8 cluster_step1 step1 cluster_step2 step2, left = mid + 1 cluster_step3 step3, right = mid - 1 cluster_step4 step4, return right nums1 5 7 7 8 8 10 indices1 left mid right indices1:left->nums1:5 indices1:mid->nums1:7_2 indices1:right->nums1:10 nums2 5 7 7 8 8 10 indices2 left mid right indices2:left->nums2:8_1 indices2:mid->nums2:8_2 indices2:right->nums2:10 nums3 5 7 7 8 8 10 indices3 left mid right indices3:left->nums3:10 indices3:mid->nums3:10 indices3:right->nums3:10 nums4 5 7 7 8 8 10 indices4 left mid right indices4:left->nums4:10 indices4:right->nums4:8_2
int findLast(int[] nums, int target) {
   int left = 0, right = n - 1, mid = 0;
   while (left <= right) {
      mid = left + (right - left) / 2;
      if (nums[mid] == target) {
         // attention (1)
         left = mid + 1;
      } else if (nums[mid] > target) {
         right = mid - 1;
      } else if (nums[mid] < target) {
         lo = mid + 1;      }
   }

   // attention (2)
   return right < 0 && nums[right] == target ? right: -1;
}

Attention

To find the last position of the target

  1. when one position is found, we need to move our search space to the right.
  2. After the loop finishes, we need to check
  • right is a valid index of the original array.
  • The element at right is equal to target.