【Python】解决Can‘t find model ‘en‘. It doesn‘t seem to be a shortcut link, a Python package or a valid

深入理解JVM(四)-执行引擎

  返回  

34. 在排序数组中查找第一个和最后一个位置

2021/7/20 15:54:46 浏览:

题目描述: 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。如果数组中不存在目标值 target,返回 [-1, -1].
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
来源: 力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
解决方案:
方法一:暴力破解法,时间复杂度为O(N).

    // 法一:暴力破解法
	public static int[] searchRange(int[] nums, int target) {
		int begin = -1, end = -1, count = 0;
		if (nums.length == 0) {
			int [] result = {begin, end};
			return result;
		}
		
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] == target) {
				end = end < i ? i : end;
				count++;
			}
		}
		if (count == 0) {
			int [] result = {begin, end};
			return result;
		}
		begin = end - count + 1;
		int[] result = {begin, end};
		return result;
	}

方法二:二分查找法,时间复杂度为O(logN).

// 法二:二分查找法
public static int[] searchRange(int[] nums, int target) {
		int begin = -1, end = -1;
		int[] result = new int[2];
		if (nums.length == 0) {
			result[0] = result[1] = -1;
			return result;
	    }
		begin = findBegin(nums, target);
		if (begin == -1) {
			end = -1;
		} else {
			end = findEnd(nums, target);
		}
		result[0] = begin;
		result[1] = end;
		return result;
	}
	
	public static int findBegin(int[] nums, int target) {
		int left = 0, right = nums.length - 1;
		while (left <= right) {
			int mid = left + (right - left) / 2;
			if (nums[mid] == target && (mid - 1 < 0 || nums[mid - 1] != target)) {
				return mid;
			} else if (nums[mid] >= target) {
				right = mid - 1;
			} else {
				left = mid + 1;
			}
		}
		return -1;
	}
	
	public static int findEnd(int[] nums, int target) {
		int left = 0, right = nums.length - 1;
		while (left <= right) {
			int mid = left + (right - left) / 2;
			if (nums[mid] == target && (mid + 1 >= nums.length || nums[mid + 1] != target)) {
				return mid;
			} else if (nums[mid] <= target) {
				left = mid + 1;
			} else {
				right = mid - 1;
			}
		}
		return -1;
	}

联系我们

如果您对我们的服务有兴趣,请及时和我们联系!

服务热线:18288888888
座机:18288888888
传真:
邮箱:888888@qq.com
地址:郑州市文化路红专路93号