1. 把数组中的 0 移到末尾
283. Move Zeroes (Easy)
1 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. |
1 | public void moveZeroes(int[] nums) { |
2. 改变矩阵维度
566. Reshape the Matrix (Easy)
1 | Input: |
1 | public int[][] matrixReshape(int[][] nums, int r, int c) { |
3. 找出数组中最长的连续 1
485. Max Consecutive Ones (Easy)
1 | public int findMaxConsecutiveOnes(int[] nums) { |
4. 有序矩阵查找
240. Search a 2D Matrix II (Medium)
1 | [ |
1 | public boolean searchMatrix(int[][] matrix, int target) { |
5. 有序矩阵的 Kth Element
378. Kth Smallest Element in a Sorted Matrix ((Medium))
1 | matrix = [ |
解题参考:Share my thoughts and Clean Java Code
二分查找解法:
1 | public int kthSmallest(int[][] matrix, int k) { |
堆解法:
1 | public int kthSmallest(int[][] matrix, int k) { |
6. 一个数组元素在 [1, n] 之间,其中一个数被替换为另一个数,找出重复的数和丢失的数
645. Set Mismatch (Easy)
1 | Input: nums = [1,2,2,4] |
1 | Input: nums = [1,2,2,4] |
最直接的方法是先对数组进行排序,这种方法时间复杂度为 O(NlogN)。本题可以以 O(N) 的时间复杂度、O(1) 空间复杂度来求解。
主要思想是通过交换数组元素,使得数组上的元素在正确的位置上。
1 | public int[] findErrorNums(int[] nums) { |
7. 找出数组中重复的数,数组值在 [1, n] 之间
287. Find the Duplicate Number (Medium)
要求不能修改数组,也不能使用额外的空间。
二分查找解法:
1 | public int findDuplicate(int[] nums) { |
双指针解法,类似于有环链表中找出环的入口:
1 | public int findDuplicate(int[] nums) { |
8. 数组相邻差值的个数
667. Beautiful Arrangement II (Medium)
1 | Input: n = 3, k = 2 |
题目描述:数组元素为 1~n 的整数,要求构建数组,使得相邻元素的差值不相同的个数为 k。
让前 k+1 个元素构建出 k 个不相同的差值,序列为:1 k+1 2 k 3 k-1 … k/2 k/2+1.
1 | public int[] constructArray(int n, int k) { |
9. 数组的度
697. Degree of an Array (Easy)
1 | Input: [1,2,2,3,1,4,2] |
题目描述:数组的度定义为元素出现的最高频率,例如上面的数组度为 3。要求找到一个最小的子数组,这个子数组的度和原数组一样。
1 | public int findShortestSubArray(int[] nums) { |
10. 对角元素相等的矩阵
766. Toeplitz Matrix (Easy)
1 | 1234 |
1 | public boolean isToeplitzMatrix(int[][] matrix) { |
11. 嵌套数组
565. Array Nesting (Medium)
1 | Input: A = [5,4,0,3,1,6,2] |
题目描述:S[i] 表示一个集合,集合的第一个元素是 A[i],第二个元素是 A[A[i]],如此嵌套下去。求最大的 S[i]。
1 | public int arrayNesting(int[] nums) { |
12. 分隔数组
769. Max Chunks To Make Sorted (Medium)
1 | Input: arr = [1,0,2,3,4] |
题目描述:分隔数组,使得对每部分排序后数组就为有序。
1 | public int maxChunksToSorted(int[] arr) { |
- 本文作者: LHS
- 本文链接: https:/LiuHuAshen.github.io/2021/06/13/数组与矩阵/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!