Leetcode面试经典150题-349.两个数组的交集

题目比较简单,散散心吧

解法都在代码里,不懂就留言或者私信

java 复制代码
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        /**先排个序 */
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int curIndex1 = 0;
        int curIndex2 = 0;
        /**先把数组的大小设置为最大可能,最大可能就是跟小数组等长 */
        int[] ans = new int[Math.min(nums1.length, nums2.length)];
        /**记录答案的有效长度 */
        int validLen = 0;
        while(curIndex1 < nums1.length && curIndex2 < nums2.length) {
            /**如果和之前的数一样就跳下一个,nums1和nums2一样的逻辑 */
            while(curIndex1 < nums1.length && curIndex1 != 0 && nums1[curIndex1] == nums1[curIndex1 - 1]) {
                curIndex1 ++;
            }
            if(curIndex2 < nums2.length && curIndex2 != 0 && nums2[curIndex2] == nums2[curIndex2 - 1]) {
                curIndex2 ++;
            }
            /**任何一个到达最后了,没必要继续了,不会再有相等的数了 */
            if(curIndex1 == nums1.length || curIndex2 == nums2.length) {
                break;
            }
            /**如果相等,记录交集,两个都跳下一个 */
            if(nums1[curIndex1] == nums2[curIndex2]) {
                ans[validLen++] = nums1[curIndex1];
                curIndex1 ++;
                curIndex2 ++;
                /**else if和else里是同一个意思,谁小谁跳下一个,因为下个数更大才有可能和另外一个相等 */
            } else if(nums1[curIndex1] > nums2[curIndex2]) {
                curIndex2 ++;
            } else {
                curIndex1 ++;
            }
        }
        /**拷贝出有效的长度 */
        return Arrays.copyOf(ans, validLen);
    }
}

这种题出现就是送你通过的,没必须追求极致,个人觉得

相关推荐
aaaameliaaa7 小时前
字符函数和字符串函数
c语言·笔记·算法
城管不管8 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯9 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡9 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯9 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang9 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One98510 小时前
高进度算法模板速记(待完善)
java·前端·算法
圣保罗的大教堂12 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
kyriewen12 小时前
面试官让我手写虚拟列表——AI生成的版本,快速滚动几下就白屏了
前端·javascript·面试
土豆.exe12 小时前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法