LeetCode上的Arry(数组)类型的题目

文章目录

      • Easy
        • 905. Sort Array By Parity
        • 832. Flipping an Image
        • 561. Array Partition I
        • 867. Transpose Matrix 矩阵的转置
        • 766. Toeplitz Matrix
        • 896. Monotonic Array 单调数组
        • 485. Max Consecutive Ones 二进制数组中最长的1
        • 888. Fair Candy Swap 交换两个数组的一个数使的两个数组和相等
        • 283. Move Zeroes 移动数组里面的0到最后面
        • 448. Find All Numbers Disappeared in an Array
        • 169. Majority Element 出现次数大于一半的元素
        • 217. Contains Duplicate 检查是否有重复的数字
        • 167. Two Sum II - Input array is sorted
        • 268. Missing Number 找出0到n中缺失的那个数字
        • 189. Rotate Array 数组往右循环移动k个位置
        • 581. Shortest Unsorted Continuous Subarray 需要排序的最短子数组的长度
        • 703. Kth Largest Element in a Stream 在数据流里面找到前K大的数
      • Medium
        • 48. Rotate Image顺时针旋转90度正方形
        • 215. Kth Largest Element in an Array 无序数组中找到第k大的数
        • 692. Top K Frequent Words
        • 347. Top K Frequent Elements
        • 442. Find All Duplicates in an Array 在O(n)时间复杂度, O(1)空间复杂度内找到数组中出现两次的数子
        • 74. Search a 2D Matrix 在排好序的矩阵里面查找数字
        • 153. Find Minimum in Rotated Sorted Array 在有序旋转数组里面查找最小值
        • 154. Find Minimum in Rotated Sorted Array II 在有序有重复旋转数组里面查找最小值
        • 560. Subarray Sum Equals K 有多少子数组的和等于给定的数字
        • 80. Remove Duplicates from Sorted Array II 不用额外的空间移除排序的重复数字


Easy


905. Sort Array By Parity

将数组的数偶数排在前面奇数排在后面。

如果直接新建一个数组的话就很容易写出代码了,但是如果要做到空间复杂度是O(1)的呢?
只要在遍历数组的时候遇到偶数数字的时候就往前放就好了。

905. Sort Array By Parity

class Solution {
    public int[] sortArrayByParity(int[] a) {
        int index = 0;
        for(int i = 0; i < a.length; i++){
            if(a[i]%2 == 0){
                int temp = a[index];
                a[index] = a[i];
                a[i] = temp;
                index++;
            }
        }
        return a;
    }
}

faster than 12.85% of Java online submissions for Sort Array By Parity.


832. Flipping an Image

832. Flipping an Image

水平翻转和颠倒矩阵。

class Solution {
    public int[][] flipAndInvertImage(int[][] a) {
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a[0].length/2; j++){
                int temp = a[i][j];
                a[i][j] = a[i][a[0].length-1-j]^1;
                a[i][a[0].length-1-j] = temp^1;
            }
            if(a[0].length%2 != 0){
                a[i][a[0].length/2] ^= 1;
            }
        }
        return a;
    }
}

faster than 46.61% of Java online submissions for Flipping an Image.


561. Array Partition I

561. Array Partition I

给定一个2n个整数的数组,你的任务是将这些整数分组为n对整数,比如说(a1,b1),(a2,b2),…,(an,bn),使得min(ai, bi)的总和最大。求这个最大的和。

先对数组进行排序,再取偶数位的和就是最小的和。时间复杂度和空间复杂度取决于使用寿什么排序方法。

class Solution {
    public int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int res = 0;
        for(int i = 0; i < nums.length; i +=2){
            res += nums[i];
        }
        return res;
    }
}

faster than 71.99% of Java online submissions for Array Partition I.


867. Transpose Matrix 矩阵的转置

867. Transpose Matrix

返回矩阵的转置。

由于这道题的矩阵不一定是正方形,所以需要新建一个矩阵,将转置后的值存到新的矩阵里面。

class Solution {
    public int[][] transpose(int[][] A) {
        if(A == null || A.length == 0 || A[0] == null || A[0].length == 0) return null;
        int row = A.length;
        int col = A[0].length;
        int[][] res = new int[col][row];
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                res[j][i] = A[i][j];
            }
        }
        return res;
    }
}

faster than 73.88% of Java online submissions for Transpose Matrix.


766. Toeplitz Matrix

766. Toeplitz Matrix

判断一个矩阵是否是Toeplitz 。如果从左上角到右下角的每个对角线具有相同的元素,则矩阵是Toeplitz。

思路是从左下角开始,逐渐往上,再往左,依次检查对角线的元素是否相等。

class Solution {
    public boolean isToeplitzMatrix(int[][] a) {
        int row = a.length-1;
        int col = 0;
        while(row != 0 || col != a[0].length-1){
            int tempRow = row;
            int tempCol = col;
            int tag = a[row][col];
            while(tempRow < a.length && tempCol < a[0].length){
                
                if(tag != a[tempRow][tempCol]) return false;
                
                tempRow++;
                tempCol++;
            }
            
            if(row > 0) row--;
            else if(col < a[0].length-1) col ++;
        }
        return true;
    }
}

faster than 6.83% of Java online submissions for Toeplitz Matrix.


896. Monotonic Array 单调数组

896. Monotonic Array

返回一个数组是不是单调数组。如果阵列单调递增或单调递减,则阵列是单调的。

一开始没什么好的想法,看了下讨论茅塞顿开…大佬的代码就是厉害…

class Solution {
    public boolean isMonotonic(int[] A) {
        boolean dec = true;
        boolean inc = true;
        for(int i = 1; i < A.length; i++){
            dec &= A[i] >= A[i-1];
            inc &= A[i] <= A[i-1];
        }
        return dec || inc;
    }
}

faster than 73.13% of Java online submissions for Monotonic Array.


485. Max Consecutive Ones 二进制数组中最长的1

485. Max Consecutive Ones

这就真的是很easy了,或许还有更加简单的方法,回头再看看。

    public int findMaxConsecutiveOnes(int[] nums) {
        int count = 0;
        int max = 0;
        for(int i : nums){
            if(i == 1){
                count++;
                max = Math.max(max, count);
            }else{
                count = 0;
            }
        }
        return max;
    }
}

faster than 26.32% of Java online submissions for Max Consecutive Ones.


888. Fair Candy Swap 交换两个数组的一个数使的两个数组和相等

888. Fair Candy Swap

返回交换的两个数。

既然要使得两个数组相等,必然是一个数组减去一个数一个数组加上一个数,那么这个数就是两个数组和的差的一半。再遍历数组找到两个这样的数就可以了。

有个可以加快速度的技巧是讲一个数组存到set里面,这样看set里面是否存在一个数就会快一点。

class Solution {
    public int[] fairCandySwap(int[] A, int[] B) {
        int sumA = 0;
        int sumB = 0;
        for(int i : A){
            sumA += i;
        }
        for(int i : B){
            sumB += i;
        }
        int tag = (sumA - sumB)/2;
        for(int a : A){
            a -= tag;
            for(int b : B){
                if(a == b) return new int[] {a + tag, b};
            }
        }
        return new int[0];
    }
}

faster than 18.94% of Java online submissions for Fair Candy Swap.


283. Move Zeroes 移动数组里面的0到最后面

283. Move Zeroes

不使用额外的空间将数组里面的0移到最后面。

使用一个变量pos记录新插入的非0数字的位置。

class Solution {
    public void moveZeroes(int[] nums) {
        int pos = 0;
        for(int i : nums){
            if(i != 0){
                nums[pos] = i;
                pos++;
            }
        }
        while(pos < nums.length){
            nums[pos] = 0;
            pos++;
        }
    }
}

faster than 56.38% of Java online submissions for Move Zeroes.


448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

给定一个整数数组,其中1≤a[i]≤n(n =数组的大小),一些元素出现两次,其他元素出现一次。 找到[1,n]包含的所有元素中在a数组中不会出现的元素。

遍历数组,因为数组元素的值是在1~n之间,所以将元素的值对应的数组索引的值置为负数。这样所有出现过的数字对应的索引的值都为负数。再遍历一次数组,那些为正的就是没有出现过的。

class Solution {
    public List findDisappearedNumbers(int[] nums) {
        List res = new ArrayList<>();
        for(int i = 0; i < nums.length; i++){
            int index = Math.abs(nums[i])-1; // 
            if(nums[index] > 0){
                nums[index] = -nums[index];
            }
        }
        
        for(int i = 0; i < nums.length; i++){
            if(nums[i] > 0){
                res.add(i+1);
            }
        }
        return res;
    }
}

faster than 92.30% of Java online submissions for Find All Numbers Disappeared in an Array.


169. Majority Element 出现次数大于一半的元素

169. Majority Element

给定大小为n的数组,找到多数元素。多数元素是出现超过⌊n /2⌋倍的元素。 您可以假设该数组非空,并且多数元素始终存在于数组中。

出现次数大于一半的数只会有一个,一次在数组删掉两个不同的数,不停滴删除,直到剩下的数只有一种(不是一个),这个数就是答案。

class Solution {
    public int majorityElement(int[] nums) {
        int num = 0;
        int count = 0;
        for(int i : nums){
            if(count == 0){
                num = i;
                count++;
            }else if(num == i){
                count++;
            }else{
                count--;
            }
        }
        
        return num;
    }
}

faster than 93.88% of Java online submissions for Majority Element.


122. Best Time to Buy and Sell Stock II 买卖股票问题

这道题就是真的很容易了,直接求相邻的数字的差,如果差大于0 就加起来,相当于一次买卖股票的操作。

class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for(int i = 1; i < prices.length; i++){
            int diff = prices[i]-prices[i-1];
            if(diff > 0) res += diff;
        }
        return res;
    }
}

faster than 99.61% of Java online submissions for Best Time to Buy and Sell Stock II.


217. Contains Duplicate 检查是否有重复的数字

217. Contains Duplicate

给定一个整数数组,查找数组是否包含任何重复项。有则返回true,否则返回false。

关于这道题:

  1. 如果不允许用额外的空间的话,只允许在原有的数组内进行操作,那就只能进行排序,然后再进行遍历看是否有相等的数字。那么在没有额外空间的排序算法的要求下,只有堆排序是符合要求的,堆排序的空间复杂度是O(1),时间复杂度是O(nlogn)。
  2. 如果要求时间复杂度是O(n)的话,就要使用额外的空间,新建一个set进行存储就可以了。

下面是第一种方法的代码:

class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums == null || nums.length == 0) return false;
        
        heapSort(nums);
        for(int i = 1; i < nums.length; i++){
            if(nums[i] == nums[i-1]) return true;
        }
        return false;
    }
    
    public void heapSort(int[] nums){
        for(int i = nums.length/2; i >= 0; i--){
            heapAdjust(nums, i, nums.length-1);
        }
        
        for(int i = nums.length-1; i > 0; i--){
            swap(nums, 0, i);
            heapAdjust(nums, 0, i-1);
        }
    }
    
    public void heapAdjust(int[] nums, int start, int end){
        int temp = nums[start];
        for(int i = start*2+1; i <= end; i *= 2){
            if(i < end && nums[i] < nums[i+1]) i++;
            if(temp >= nums[i]) break;
            nums[start] = nums[i];
            start = i;
        }
        nums[start] = temp;
    }
    
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

faster than 38.20% of Java online submissions for Contains Duplicate.


167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted

因为是已经排序好的数组,用三明治夹:即两边夹

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int i = 0;
        int j = numbers.length-1;
        while(i

faster than 68.77% of Java online submissions for Two Sum II - Input array is sorted.


268. Missing Number 找出0到n中缺失的那个数字

268. Missing Number

给定一个包含n个不同数字的数组,由0,1,2,…,n组成,找到数组中缺少的数字。

利用异或的特点:

  • 两个相同的数异或的结果为0
  • 0异或数字等于原数字
class Solution {
    public int missingNumber(int[] nums) {
        int missing = 0;
        for(int i = 1; i <= nums.length; i++){
            missing ^= i;
        }
        for(int i = 0; i < nums.length; i++){
            missing ^= nums[i];
        }
        return missing;
    }
}

faster than 69.45% of Java online submissions for Missing Number.


189. Rotate Array 数组往右循环移动k个位置

189. Rotate Array

要求空间复杂度是O(1)

最先想到的方法是,每次向右循环移动1个位置,循环k次,代码如下:

虽然能过,但是这样子就太慢了。于是就看看了一下套理论里面的答案,太聪明了:有以下这种思路:

  1. 先全部反转数组
  2. 反转前面k个
  3. 反转后面的

smart solution
example:
1234567
reverse all to
7654321
reverse 0 to k-1
5674321
reverse k-1 to n
5671234

我的代码:

class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        for(int i = 0; i < k; i++){
            rotate(nums);
        }
    }
    
    public void rotate(int[] nums){
        int temp = nums[0];
        for(int i = 1; i < nums.length; i++){
            int cur = nums[i];
            nums[i] = temp;
            temp = cur;
        }
        nums[0] = temp;
    }
}

faster than 10.68% of Java online submissions for Rotate Array.

聪明的代码:

public void rotate(int[] nums, int k) {
    k %= nums.length;
    reverse(nums, 0, nums.length - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, nums.length - 1);
}

public void reverse(int[] nums, int start, int end) {
    while (start < end) {
        int temp = nums[start];
        nums[start] = nums[end];
        nums[end] = temp;
        start++;
        end--;
    }
}

581. Shortest Unsorted Continuous Subarray 需要排序的最短子数组的长度

581. Shortest Unsorted Continuous Subarray

如图,红色这个区域就是最短的距离。

LeetCode上的Arry(数组)类型的题目_第1张图片

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int l = 0;
        int r = 0;
        int max =Integer.MIN_VALUE;
        int min =Integer.MAX_VALUE;
        for(int i = 0; i < nums.length; i++){
            max = Math.max(nums[i], max);
            if(nums[i] < max) l = i;
        }
        for(int i =nums.length-1 ; i >= 0; i--){
            min = Math.min(nums[i], min);
            if(nums[i] > min) r = i;
        }
        if(l == r) return 0;
        return l-r+1;
    }
}

faster than 32.44% of Java online submissions for Shortest Unsorted Continuous Subarray.


703. Kth Largest Element in a Stream 在数据流里面找到前K大的数

703. Kth Largest Element in a Stream

用堆来进行存储K大的数,并用堆排序。

需要注意的是一些特殊输入。比如初始的数组是空的,这是就需要用Integer.MIN_VALUE来先对堆进行填充,这一点很重要。

class KthLargest {
    
    int[] heap;

    public KthLargest(int k, int[] nums) {
        heap = new int[k];
        Arrays.fill(heap, Integer.MIN_VALUE);
        int index = 0;
        for(int i : nums){
            if(index < k){
                heap[index] = i;
                heapInsert(heap, index);
                index++;
            }else{
                if(heap[0] < i){
                    heap[0] = i;
                    heapify(heap, 0, k-1);
                }
            }
        }
        for(int i = 0; i < k; i++){
            heapify(heap, i, k-1);
        }
    }
    
    public int add(int val) {
        if(val > heap[0]){
            heap[0] = val;
            heapify(heap, 0, heap.length-1);
        }
        return heap[0];
    }
    
    public void swap(int[] heap, int i, int j){
        int temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }
    
    public void heapInsert(int[] heap, int i){
        int parent = 0;
        while(i > 0){
            parent = (i-1)/2;
            if(heap[i] < heap[parent]){
                swap(heap, i, parent);
                i = parent;
            } else {
                break;
            }
        }
    }

    public void heapify(int[] heap, int start, int end){
        int left = start*2+1;
        int right = start*2+2;
        int smallest = start;
        while(left <= end){
            if(heap[left] < heap[start]){
                smallest = left;
            }
            
            if(right <= end && heap[right] < heap[smallest]){
                smallest = right;
            }
            
            if(smallest != start){
                swap(heap, smallest, start);
            } else {
                break;
            }
            
            start = smallest;
            left = start*2+1;
            right = start*2+2;
        }
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

faster than 41.82% of Java online submissions for Kth Largest Element in a Stream.


Medium


48. Rotate Image顺时针旋转90度正方形

48. Rotate Image

遇到正方形的题目有一种方法是分圈处理,就是先处理最外一圈,再处理次外圈,一直到最里面的一圈。通过左上角的点和右下角的点进行圈的标记。

class Solution {
    public void rotate(int[][] a) {
        int rightTopRow = 0;
        int rightTopCol = 0;
        int leftDownRow = a.length-1;
        int leftDownCol = a[0].length-1;
        while(rightTopRow < leftDownRow){
            rotate(a, rightTopRow++, rightTopCol++, leftDownRow--, leftDownCol--);
        }
    }
    
    public void rotate(int[][] a, int rightTopRow, int rightTopCol, int leftDownRow, int leftDownCol){
        int count = leftDownRow - rightTopRow;
        int temp = 0;
        for(int i = 0; i < count; i++){
            temp = a[rightTopRow][rightTopCol+i];
            a[rightTopRow][rightTopCol+i] = a[leftDownRow-i][rightTopCol];
            a[leftDownRow-i][rightTopCol] = a[leftDownRow][leftDownCol-i];
            a[leftDownRow][leftDownCol-i] = a[rightTopRow+i][leftDownCol];
            a[rightTopRow+i][leftDownCol] = temp;
        }
    }
}

faster than 44.74% of Java online submissions for Rotate Image.


215. Kth Largest Element in an Array 无序数组中找到第k大的数

215. Kth Largest Element in an Array

这类型的题,要习惯想到用堆排序:

  • 无序数组中最小的k个数
  • N个数组中最大的k个数
  • 出现次数的top K
public class Solution {
    public int findKthLargest(int[] nums, int k) {
        k = nums.length - k + 1;
        int[] heap = new int[k];
        for(int i = 0; i < k; i++){
            insert(heap, nums[i], i);
        }
        for(int i = k; i < nums.length; i++){
            if(nums[i] < heap[0]){
                heap[0] = nums[i];
                heapify(heap, 0, k);
            }
        }
        return heap[0];
    }
    
    public void insert(int[] nums, int value, int pos){
        nums[pos] = value;
        while(pos != 0){
            int parent = (pos-1)/2;
            if(nums[parent] < nums[pos]){
                swap(nums, parent, pos);
                pos = parent;
            } else {
                break;
            }
        }
    }
    
    public void heapify(int[] nums, int index, int size){
        int l = index*2 + 1;
        int r = index*2 + 2;
        int largest = index;
        while(l < size){
            if(nums[l] > nums[largest]){
                largest = l;
            }
            if(r < size && nums[r] > nums[largest]){
                largest = r;
            }
            if(largest != index){
                swap(nums, largest, index);
            } else {
                break;
            }
            index = largest;
            l = index*2 + 1;
            r = index*2 + 2;
        }
    }
    
    public void swap(int[] nums, int l, int r){
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
    }
}

faster than 81.38% of Java online submissions for Kth Largest Element in an Array.


692. Top K Frequent Words

692. Top K Frequent Words

同样是要利用到堆排序的思想。

题目有一点要求是对于次数相同的字符串要按照字典排序。于是用到 compareTo 的方法:
a > aa
“a”.compareTo(“aa”) < 0

class Solution {
    public List topKFrequent(String[] words, int k) {
        Map map = new HashMap<>();
        
        for(String s : words){
            if(map.containsKey(s)){
                map.put(s, map.get(s) + 1);
            }else{
                map.put(s, 1);
            }
        }
        
        Node[] heap = new Node[k];
        
        int index = 0;
        
        
        // a > aa
        // "a".compareTo("aa") < 0
        for(Map.Entry m : map.entrySet()){
            String key = m.getKey();
            int value = m.getValue();
            
            Node node = new Node(key, value);
            
            if(index < k){
                heap[index] = node;
                heapInsert(heap, index);
                index++;
            }else{
                if(value > heap[0].value || (value == heap[0].value && key.compareTo(heap[0].key) < 0)){
                    heap[0] = node;
                    heapify(heap, 0, k-1);
                }
            }
        }
        
        for(int i = heap.length - 1; i > 0; i--){
            swap(heap, 0, i);
            heapify(heap, 0, i-1);
        }
        
        List res = new ArrayList<>();
        
        for(int i = 0; i < heap.length; i++){
            res.add(heap[i].key);
        }
        
        return res;
    }
    
    public void heapInsert(Node[] heap, int i){
        int parent = 0;
        while(i > 0){
            parent = (i - 1)/2;
            if(heap[i].value < heap[parent].value){
                swap(heap, i, parent);
                i = parent;
            }else if (heap[i].value == heap[parent].value && heap[i].key.compareTo(heap[parent].key) > 0){
                swap(heap, i, parent);
                i = parent;
            }else{
                break;
            }
        }
    }
    
    public void heapify(Node[] heap, int start, int end){
        int left = start * 2 + 1;
        int right = start * 2 + 2;
        int smallest = 0;
        while(left <= end){
            if(heap[left].value < heap[start].value || (heap[left].value == heap[start].value && heap[left].key.compareTo(heap[start].key) > 0)){
                smallest = left;
            }
            
            if(right <= end && heap[right].value < heap[smallest].value){
                smallest = right;
            }
            
            if(right <= end && (heap[right].value == heap[smallest].value && heap[right].key.compareTo(heap[smallest].key) > 0)){
                smallest = right;
            }
            
            if(smallest != start){
                swap(heap, smallest, start);
            }else{
                break;
            }
            
            start = smallest;
            left = start * 2 + 1;
            right = start * 2 + 2;
            
        }
    }
    
    public void swap(Node[] heap, int a, int b){
        Node temp = heap[a];
        heap[a] = heap[b];
        heap[b] = temp;
    }
    
}

class Node {
    public String key;
    public int value;
    
    public Node(String key, int value){
        this.key = key;
        this.value = value;
    }
}

faster than 61.00% of Java online submissions for Top K Frequent Words.


347. Top K Frequent Elements

347. Top K Frequent Elements

同样是用堆排序的方法。

class Solution {
    public List topKFrequent(int[] nums, int k) {
        Map map = new HashMap<>();
        for(int i : nums){
            if(map.containsKey(i)){
                map.put(i, map.get(i)+1);
            }else{
                map.put(i, 1);
            }
        }
        
        Node[] heap = new Node[k];
        int index = 0;
        
        for(Map.Entry e : map.entrySet()){
            int key = e.getKey();
            int value = e.getValue();
            Node node = new Node(key, value);
            if(index < k){
                heap[index] = node;
                heapInsert(heap, index);
                index++;
            } else {
                if(value > heap[0].value){
                    heap[0] = node;
                    heapify(heap, 0, k-1);
                }
            }
        }
        
        for(int i = k-1; i > 0; i--){
            swap(heap, 0, i);
            heapify(heap, 0, i-1);
        }
        
        List res = new ArrayList<>();
        
        for(int i = 0; i < k; i++){
            res.add(heap[i].key);
        }
        
        return res;
    }
    
    public void heapInsert(Node[] heap, int i){
        int parent = 0;
        while(i > 0){
            parent = (i-1)/2;
            if(heap[i].value < heap[parent].value){
                swap(heap, i, parent);
                i = parent;
            } else {
                break;
            }
        }
    }
    
    public void heapify(Node[] heap, int start, int end){
        int left = start*2+1;
        int right = start*2+2;
        int smallest = start;
        while(left <= end){
            if(heap[left].value < heap[start].value){
                smallest = left;
            }
            
            if(right <= end && heap[right].value < heap[smallest].value){
                smallest = right;
            }
            
            if(smallest != start){
                swap(heap, smallest, start);
            } else {
                break;
            }
            
            start = smallest;
            left = start*2+1;
            right = start*2+2;
        }
    }
    
    public void swap(Node[] heap, int i, int j){
        Node temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }
}

class Node{
    int key;
    int value;
    
    public Node(int key, int value){
        this.key = key;
        this.value = value;
    }
}

faster than 45.83% of Java online submissions for Top K Frequent Elements.


442. Find All Duplicates in an Array 在O(n)时间复杂度, O(1)空间复杂度内找到数组中出现两次的数子

442. Find All Duplicates in an Array

将出现过的数字对应数组的数字置为负的,表示出现过。

class Solution {
    public List findDuplicates(int[] nums) {
        if(nums == null || nums.length == 0) return new ArrayList<>();
        List res = new ArrayList<>();
        for(int i = 0; i < nums.length; i++){
            int index = Math.abs(nums[i]);
            if(nums[index-1] > 0){
                nums[index-1] = -nums[index-1];
            }else{
                res.add(index);
            }
        }
        return res;
    }
}

faster than 51.29% of Java online submissions for Find All Duplicates in an Array.


74. Search a 2D Matrix 在排好序的矩阵里面查找数字

74. Search a 2D Matrix

从右上角开始查找

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0){
            return false;
        }
        int row = 0;
        int col = matrix[0].length-1;
        while(row < matrix.length && col >= 0){
            if(matrix[row][col] == target){
                return true;
            }else if(matrix[row][col] > target){
                col--;
            }else{
                row++;
            }
        }
        return false;
    }
}

faster than 12.47% of Java online submissions for Search a 2D Matrix.


153. Find Minimum in Rotated Sorted Array 在有序旋转数组里面查找最小值

153. Find Minimum in Rotated Sorted Array

有三个参数标记数组最右边,中间,最左边的数字,分别是:low, mid, high
因为有序数组,所以会出现一个拐点:

  1. 拐点左边的值 > 数组第low个数字
  2. 拐点右边的值 < 数组第low个数字

于是:

  1. mid的值 > low的值,左边寻找拐点
  2. mid的值 < low的值, 右边变寻找拐点
  3. 停止寻找的条件:mid的值 > mid+1的值(最小则为mid+1)或者mid-1的值 > mid的值(最小为mid)
class Solution {
    public int findMin(int[] nums) {
        if(nums == null || nums.length == 0){
            return -1;
        }
        if(nums.length == 1){
            return nums[0];
        }
        int low = 0;
        int high = nums.length-1;
        if(nums[low] < nums[high]){
            return nums[low];
        }
        while(low <= high){
            int mid = (low + high)/2;
            if(nums[mid] > nums[mid+1]){
                return nums[mid+1];
            }else if(nums[mid-1] > nums[mid]){
                return nums[mid];
            }
            
            if(nums[low] < nums[mid]){
                low = mid+1;
            }else{
                high = mid-1;
            }
        }
        return -1;
    }
}

faster than 100.00% of Java online submissions for Find Minimum in Rotated Sorted Array.


154. Find Minimum in Rotated Sorted Array II 在有序有重复旋转数组里面查找最小值

154. Find Minimum in Rotated Sorted Array II

这道题和上面有一个不一样就是数组里面有重复的数字。
所以只需要再加上处理nums[low] = nums[mid] = nums[high]的逻辑就行。

class Solution {
    public int findMin(int[] nums) {
        int low = 0;
        int high = nums.length-1;
        int mid = 0;
        while(low < high){
            if(low == high-1){
                break;
            }
            
            if(nums[low] < nums[high]){
                return nums[low];
            }
            
            mid = (low + high)/2;
            
            if(nums[low] > nums[mid]){
                high = mid;
                continue;
            }
            
            if(nums[low] < nums[mid]){
                low = mid;
                continue;
            }
            
            // nums[low] = nums[mid] = nums[high]
            while(low < mid){
                if(nums[low] == nums[mid]){
                    low++;
                } else if(nums[low] < nums[mid]){
                    return nums[low];
                } else {
                    high = mid;
                    break;
                }
            }
            
        }
        return Math.min(nums[low], nums[high]);
    }
}

faster than 100.00% of Java online submissions for Find Minimum in Rotated Sorted Array II.


560. Subarray Sum Equals K 有多少子数组的和等于给定的数字

560. Subarray Sum Equals K

主要有个思想是用一个map来存:

  • key:子数组的和
  • value:这个和可以由多少种子数组累加

关于用map的存信息的思想也可以用在求最长子数组的和等于给定的数,这个子数组最长长度等于多少。

class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        int sum = 0;
        
        Map map = new HashMap<>();
        map.put(0,1);
        
        for(int i : nums){
            sum += i;
            if(map.containsKey(sum-k)){
                count += map.get(sum-k);
            }
            
            map.put(sum, map.getOrDefault(sum, 0)+1);
        }
        
        return count;
    }
}

faster than 51.41% of Java online submissions for Subarray Sum Equals K.


80. Remove Duplicates from Sorted Array II 不用额外的空间移除排序的重复数字

80. Remove Duplicates from Sorted Array II

class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        int index = 1;
        int count = 1;
        int n = nums[0];
        for(int i = 1; i < nums.length; i++){
            if(nums[i] == n){
                count++;
            } else {
                n = nums[i];
                count = 1;
            }
            if(count < 3){
               nums[index] = n;
                index++;
            }
        }
        return index;
        
    }
}

faster than 13.58% of Java online submissions for Remove Duplicates from Sorted Array II.

你可能感兴趣的:(LeetCode题的自我理解)