[leetcode] LeetCode周练Contest-34代码解析
概要: 总共4个题,一个半小时的时间安排。题目分级为,两个easy,一个medium,一个hard。
第一题 598. Range Addition II
题目描述:
Given an m * n matrix M initialized with all 0's and several update operations.
Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.
You need to count and return the number of maximum integers in the matrix after performing all the operations.
Example 1:
Input: m = 3, n = 3 operations = [[2,2],[3,3]] Output: 4 Explanation: Initially, M = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] After performing [2,2], M = [[1, 1, 0], [1, 1, 0], [0, 0, 0]] After performing [3,3], M = [[2, 2, 1], [2, 2, 1], [1, 1, 1]] So the maximum integer in M is 2, and there are four of it in M. So return 4.
这一题是easy,要求统计矩阵最大值的个数,
可以发现,矩阵越靠近左上角的元素值越大,因为要加1的元素 行和列索引是从0开始的。
那么只需要找到操作次数最多的元素位置即可。而操作次数最多的元素肯定是偏向于靠近矩阵左上角的。
其实就是求a和b的最小值,然后框定的范围内的值一定都是最大的,个数就是n*m。
第二题 599. Minimum Index Sum of Two Lists
题目描述:
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
也是一道开胃菜,用一个unordered_map来维护即可。
第三题 565. Array Nesting
题目描述:
A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0, N - 1].
Sets S[K] for 0 <= K < N are defined as follows:
S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }.
Sets S[K] are finite for each K and should NOT contain duplicates.
Write a function that given an array A consisting of N integers, return the size of the largest set S[K] for this array.
同样是一个开胃菜的题目,不过这一次LeetCode的评定这个题是medium难度,维护一个同样大小的数组来表示有哪些数被循环访问过,然后顺序遍历所有的值,统计一下最大值即可
第四题 600. Non-negative Integers without Consecutive Ones
题目描述:
Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.
这道题判断一个数的二进制表达是否有连续的1,可以用原始值和原始值向左循环移动一位的结果做一个与运算,如果结果为0即满足条件,反正则不满足;
第一次用了一个顺序统计的方法来做,结果显然会超时,因为n的取值是10的9次方级别的。所以后面考虑统计每一个以每一位开头为1,结尾为任意值的集合,其中不满足条件的有多少个数,最后用总数去减即可得到结果(代码暂时还未完善)