1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| package algorithm;
import java.util.Arrays;
public class FindFirstAndLastPositionOfElementInSortedArray {
public static int[] searchRange(int[] nums, int target) {
int[] result;
int length = nums.length; int left = 0; int right = length - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] == target) { left = right = mid; while (
} left++; while (++right < length && nums[right] == target) {
} right result = new int[]{left, right}; return result; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } }
result = new int[]{-1, -1}; return result; }
public static void main(String[] args) {
//nums = [5,7,7,8,8,10], target = 8 int[] nums = new int[]{5,7,7,8,8,10}; int target = 8; System.out.println(Arrays.toString(searchRange(nums, target)));
//nums = [5,7,7,8,8,10], target = 6 nums = new int[]{5,7,7,8,8,10}; target = 6; System.out.println(Arrays.toString(searchRange(nums, target)));
//nums = [], target = 0 nums = new int[]{}; target = 0; System.out.println(Arrays.toString(searchRange(nums, target))); }
}
|