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
  • 相关阅读:
    Chapter01_前言、入门程序、常量、变量
    面向对象知识点总结
    Java快捷键
    上线
    docker
    分页,过滤,搜索,排序
    Celery
    django-redis 缓存使用
    前台登录注册修订
    短信注册接口
  • 原文地址:https://www.cnblogs.com/yawenw/p/12952983.html
Copyright © 2011-2022 走看看