目录 Shrinking Number Line (LC 910)··························································· 2 Odd Strings······················································································· 3 K-Subarrays (LC 974)········································································· 4 Sprint Training (LC370)······································································· 5 Do they belong·················································································· 6 Visiting cities····················································································· 8 Count group size················································································ 9 longest subarray with sum <= k···························································· 11 1 Shrinking Number Line (LC 910) 先排序。 一定会有一个分界点,从它开始往右全部减 k, 左边的全部加 k,这个分界点可以在任何一个 point。 最左边的 left = nums[0] + k,最右边为 nums[nums.size()-1]-k 如果这个点 i 是分界点,那么最小值即为 min(nums[i]-k, left),最大值 max(nums[i-1]+k,right) 那对于每一个点,我们假设那个就是分界点,求出这种情况下得 max 和 min 的 diffrence,找其中 最小的 2 Odd Strings 给出一个字符串数列 array,一个整数 m, 以及一个求值方法,判断该数列对应的值是否为偶数,字 符串 中仅包含 [a-z] 求值方法为: 对于单个字符串,其值为每个字符对应的 ASCII 码的 m 次方的乘积 对于整个数列,其值为每个字符串对应的值之和 m ≤ 10^9 思路:累乘如果有偶数那结果就是偶数,这样好像对于 m 没要求了 3 K-Subarrays (LC 974) 给出一个数列 array,一个整数 k,对于 array 的任一连续子数列,若其元素值之和能被 k 整除,则 称其为 array 的 k-subarray 求数列中 k-subarray 的总个数 需要 O(n) 复杂度 思路:prefix sum 这里先确保 currentSum 是整数,然后 hashtable 的 key 是 currenSum%k, 只有可能是 0 - k-1 4 Sprint Training (LC370) 给你一个 array,对每两个相邻位置 i,j,认为 [i, j] 都被遍历到一次,求被遍历次数最多的 indices 中最小的 index。 5 Do they belong 给定三角形 3 个点的坐标,在给定一个点 (x,y),判断该点是否在三角形中。 6 7 Visiting cities 8 Count group size 有 n 个同学,有 k 个 query,每个 query 可能是 Friend 或 Total,如果是 friend,把对应 student1 和 student2 所在的 group 联合起来,如果是 total,求两个 student 分别所在 group size 之和。 要注意的是如果两个人在同一个 group,只能算一次。另外并查集的 count size 需要加速,最好用 一个数组存起来,merge 时更新。另外最好也用上路径压缩,不然后面的 case 会 TLE。 9 10 longest subarray with sum <= k 给定一个 array, 然后给定一个 k, 找出 longest subarray with sum <= k, 返回长度。 用 sliding window, maintain 一个 current window sum, 如果 sum > k 就移 s pointer, 每次都 update 一下 globalMax 11