import java.util.Arrays; /** * 功能描述 * * @author ASUS * @version 1.0 * @Date 2022/8/27 */ public class Main06 { public static void main(String[] args) { /* 给定一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。 如果数组中不存在目标值 target,返回 [-1, -1]。 设计并实现时间复杂度为 O(log n) 的算法解决此问题。 示例 1: 输入:nums = [5,7,7,8,8,9,8,10], target = 8 输出:[3,4] */ int[] nums = new int[]{5, 7, 7, 8, 8, 9, 10}; int target = 7; getTarget2(nums, target); } /** * 获取目标值 * * @param nums * @param target * @return */ private static void getTarget(int[] nums, int target) { int start = -1; int end = -1; for (int i = 0; i < nums.length; i++) { if (nums[i] == target && start == -1) { start = i; break; } } for (int i = nums.length - 1; i >= 0; i--) { if (nums[i] == target && end == -1) { end = i; break; } } System.out.println(Arrays.asList((start + "," + end).split(","))); } /** * 获取目标值 * * @param nums * @param target * @return */ private static void getTarget2(int[] nums, int target) { int start; int end; String string = Arrays.toString(nums).replace(",", "").replace(" ", ""); string = string.substring(1, string.length() - 1); System.out.println(string); start = string.indexOf(String.valueOf(target)); end = string.lastIndexOf(String.valueOf(target)); System.out.println(Arrays.asList((start + "," + end).split(","))); } }
标签:end,target,nums,int,23,start,LeetCode,string,刷题 From: https://www.cnblogs.com/chch213/p/16630994.html