Leetcode周赛187

  1. Destination city
    You are given the array paths, where paths[i] = [city A_i, city B_i] means there exists a direct path going from city A_i to city B_i. Return the destination city, that is, the city without any path outgoing to another city.

分析:给定i路径A->B,把所有路程的终点B加入集合,然后删除那些可以去到下一个地方的路程终点,得到的就是最后的总终点(不会从这个地方开始去任何地方)。

	public String destCity_1(List<List<String>> paths) {
		Set<String> set = new HashSet<>();

		// add to
		for (List<String> l : paths)
			set.add(l.get(1));

		// remove from
		for (List<String> l : paths)
			set.remove(l.get(0));

		return set.iterator().next();
	}

这个题是简单题,但是一开始没想到怎么做。Hmmm,为什么呢?没有思路,以为是一道图论相关的题。我觉得还是对于出题的模式和数据结构的直觉不够,多加针对性练习吧。

  1. Check If All 1’s Are at Least Length K Places Away
    Given an array nums of 0s and 1s and an integer k, return True if all 1’s are at least k places away from each other, otherwise return False.
    nums = [1,0,0,0,1,0,0,1], k = 2
    return true; 因为所有的1都相隔了>=2的距离。
 public static boolean kLengthApart(int[] nums, int k) {
		int cum = 100000;
        
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] == 0) {
				cum++;
			} else {
				if (cum < k) {
					return false;
				}
				cum = 0;
			}
        }
		return true;
	}

扫描数组,记录0的个数,如果超过了就返回

  1. Q1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
    Given an array of integers nums and an integer limit, return the size of the longest continuous subarray such that the absolute difference between any two elements is less than or equal to limit.
    返回子数组内最大绝对差值小于limit的 最长子数组长度。

用到了双向队列的思路。

// https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/609743/Java-Detailed-Explanation-Sliding-Window-Deque-O(N)
	public int longestSubarray(int[] nums, int limit) {
		Deque<Integer> maxq = new ArrayDeque<>();
		Deque<Integer> minq = new ArrayDeque<>();
		int res = 1; // min length is array containing single element

		int l = 0;

		for (int r = 0; r < nums.length; r++) {
			// popmax q
			while (!maxq.isEmpty() && maxq.peekLast() < nums[r]) {
				maxq.removeLast();
			}
			maxq.addLast(nums[r]);

			// min q
			while (!minq.isEmpty() && minq.peekLast() > nums[r]) {
				minq.removeLast();
			}
			minq.addLast(nums[r]);

			// remove head for both q if hit limit
			while (maxq.peekFirst() - minq.peekFirst() > limit) {
				if (maxq.peekFirst() == nums[l])
					maxq.pollFirst();
				if (minq.peekFirst() == nums[l])
					minq.pollFirst();

				l++; // shift left pointer to right
			}
			res = Math.max(res, r - l + 1);
		} // end for
		return res;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值