zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge23 之 双指针法、ArrayList转数组

    本题使用双指针法。如果A[0]的端点最小,则它只能与B[0]相交。之后,我们可以丢弃A[0],因为它无法与其他任何东西相交。 类似地,如果B[0]的端点最小,则它只能与A[0]相交,并且我们可以在之后丢弃B[0],因为它无法与其他任何相交。 我们使用两个指针i和j来虚拟地重复管理“丢弃” A[0]或B[0]。

    语法补充:List转数组

    //一维
    List<String> testList1 = new ArrayList<>();
    String[] array1 = testList1.toArray(new String[testList1.size()]);
    
    //二维
    List<int[]> testList2 = new ArrayList<>();
    int[][] array2 = testList2.toArray(new int[testList2.size()][]);

    JAVA

    class Solution {
        public int[][] intervalIntersection(int[][] A, int[][] B) {
            List<int[]> res = new ArrayList<>();
            int i = 0;
            int j = 0;
            while(i < A.length && j < B.length){
                int low = Math.max(A[i][0], B[j][0]);
                int high = Math.min(A[i][1], B[j][1]);
                if(low <= high){
                    res.add(new int[]{low, high});
                }
                if(A[i][1] < B[j][1]) i++;
                else j++;
            }
            //List转二维数组
            return res.toArray(new int[res.size()][]);
        }
    }

    Python

    class Solution:
        def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
            res = []
            i = 0
            j = 0
            while i < len(A) and j < len(B):
                low = max(A[i][0], B[j][0])
                high = min(A[i][1], B[j][1])
                if low <= high:
                    res.append([low,high])
                if A[i][1] < B[j][1]:
                    i += 1
                else:
                    j += 1
            return res
  • 相关阅读:
    重启sqlserver服务命令
    k8s学习
    collection包1.1.0都升级了什么功能
    Golang项目的测试实践
    一个让业务开发效率提高10倍的golang库
    GopherChina第二天小结
    GopherChina第一天小结
    slice是什么时候决定要扩张?
    史上最快的后台搭建框架
    gorm的日志模块源码解析
  • 原文地址:https://www.cnblogs.com/yawenw/p/12952983.html
Copyright © 2011-2022 走看看