LeetCode——Intersection of Two Linked Lists

AI时代,程序员何去何从?别慌,看完这篇你就明白了 AI时代程序员的发展方向 摘要:随着AI代码助手的普及,程序员行业面临变革。本文通过实际案例展示AI写代码的能力与局限:AI能生成基础功能代码(如RESTful API、数据处理脚本),但缺乏业务理解、系统设计和复杂逻辑处理能力。程序员的核心价值在于需求分析、架构设计、性能优化等高层能力。未来程序员应: 掌握AI工具提升效率 专注于创新和架构设计 培养业务理解能力 持续学习新技术 AI不会取代程序员,但会淘汰不会使用AI的程序员。建议开发者拥抱AI工具,将其作为助手而非威胁,聚焦高价值工作。 阅读详情
LeetCode——Intersection of Two Linked Lists

# 160

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:

    If the two linked lists have no intersection at all, return null.
    The linked lists must retain their original structure after the function returns.
    You may assume there are no cycles anywhere in the entire linked structure.
    Your code should preferably run in O(n) time and use only O(1) memory.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

这一题的目的是找出两个链表的相交结点。一开始思路是利用两个指针去遍历两个链表,但是这样每次走相同的步数,如果两个链表长度不一样,是没办法比较到同一结点的。所以为了解决这个问题,想到了先求两个链表的长度差,让长链表的指针先走到对应的位置,然后两个指针一起走。

  • C++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA == NULL || headB == NULL)
            return NULL;
        int lenA = getlength(headA);
        int lenB = getlength(headB);
        if(lenA > lenB) {
            for(int i = 0;i < lenA - lenB;i++) {
                headA = headA -> next;
            }
        }
        else {
            for(int i = 0;i < lenB - lenA;i++) {
                headB = headB -> next;
            }
        }
        while(headA != NULL && headB != NULL) {
            if(headA == headB) {
                return headA;
            }
            else if(headA != headB) {
                headA = headA -> next;
                headB = headB -> next;
            }
        }
       return NULL; 
    }
    int getlength(ListNode *head) {
        int len = 0;
        while(head != NULL) {
            len++;
            head = head -> next;
        }
        return len;
    }
};

还有一种思路,定义两个指针,每个都从头遍历,到了链表终点就从另一个链表初始点开始遍历。两个链表如果相交,肯定会在相交点相遇,因为路程是相同的。如果不相交,两个指针都会在彼此链表空结点结束。

  • C++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (!headA || !headB) return NULL;
        ListNode *a = headA, *b = headB;
        while (a != b) {
            a = a ? a->next : headB;
            b = b ? b->next : headA;
        }
        return a;
    }
};
SQL面试题——抖音SQL面试题 股票波峰波谷 这个题目的难度比较低,我们是用lead 和 lag 两个函数就可以搞定,也就是在一个SQL 里面同时使用多个函数,问题的考查点在于对边界的考虑。 阅读详情

相关推荐

深入了解BPM及BPM业务流程管理系统

BPM 即业务流程管理,是一种以规范化的构造端到端的卓越业务流程为中心,以持续地提高组织业务绩效为目的的系统化方法。它涵盖了业务流程的整个生命周期,包括流程的设计、执行、监控、分析和优化。BPM 作为一种先进的管理方法,对于企业提高运营效率、降低成本、提升客户满意度和增强竞争力具有重要意义。BPM 流程管理系统为企业实现 BPM 提供了强大的工具和支持,而 F2BPM 流程管理平台以其先进的技术架构、丰富的功能模块、简单易用的操作界面和强大的定制能力,成为企业实现业务流程管理的理想选择。

Stone3625的博客 2958

LeetCode力扣 160. 相交链表 Intersection of Two Linked Lists 题解代码 JavaScript

问题https://leetcode-cn.com/problems/intersection-of-two-linked-lists/ 练习使用JavaScript解答 /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} headA * @par.

Coding home - 漂流瓶jz 565

业务建模核心方法论与DDD实战指南

业务建模是系统设计的核心环节,通过抽象业务逻辑和流程关系构建数字化蓝图。其核心原理在于解构价值链、定义协作模型和封装业务规则,采用领域驱动设计(DDD)等方法建立业务与技术的统一语言。在电商、金融等高复杂度场景中,精准的业务建模可提升60%以上的流程效率,避免因早期建模缺陷导致的架构返工。典型技术实现涉及状态机模式、规则引擎等组件,其中Drools规则引擎能有效管理50+业务规则,而事件溯源模式则为金融等强审计需求场景提供解决方案。现代工程实践更结合数字孪生技术,实现业务系统的实时仿真与优化。

weixin_29443363的博客 197

[LeetCode] Intersection of Two Linked Lists 题解

Intersection of Two Linked Lists也是LeetCode的Linked List Tag下的一道题,网上流传着多种做法。

AllZone 460

PHP特性知识点总结

(1)类型转换之前提到过的是字符串转为整型。其实php手册里面提到了各种类型的转换。先把他放在这里。我们按照php手册上的顺序来介绍,只介绍几个比较常用的。①转化为bool②转化为整型int。

m0_73605862的博客 1299

基于QT+Halcon实现线序识别

一、线序识别算法步骤。 1.按照检测区域m_pItem1的外接矩形(rtBount)的大小, 截取感兴趣区域图像hRoi。 2.把截取出来的感兴趣区域图像hRoi, 分离出R、G、B三个通道hRed、hGreen、hBlue。 3.把hRed、hGreen、hBlue三个通道转换成cielab颜色空间, 得到hChannelL、hChannelA、hChannelB三个颜色图。 4.设m_pItem1的宽为iItemW, 高为iItemH. 分别申请大小为iItemW的pSumL、pSumA、pSumB内

专注现代C++实战,从核心语法到高性能编程,助力开发者深入掌握系统级编程精髓。 1755

LeetCode--LinkedList--160. Intersection of Two Linked Lists(Easy)

160. Intersection of Two Linked Lists(Easy) 题目地址https://leetcode.com/problems/intersection-of-two-linked-lists/ Write a program to find the node at which the intersection of two singly linked lists be...

weixin_30856725的博客 207

基于Transformer模型实现交通流量时序预测(PyTorch版)

Transformer模型,作为一种基于自注意力机制的深度学习模型,最初在自然语言处理领域取得了突破性进展,其出色的长距离依赖关系捕捉能力使其在处理时序数据时也表现出色。将Transformer模型应用于交通流量时序预测,可以充分利用其优势,实现对交通流量更加精准、高效的预测。

时序笔记 2577

LeetCode Intersection of Two Linked Lists

原题链接在这里:https://leetcode.com/problems/intersection-of-two-linked-lists/ 思路: 1. 找到距离各自tail 相同距离的起始ListNode,可以通过两个pointer,长的那个先移动Math.abs(lenA-lenB). 2. 两个pointer各自移动直到找到相同的ListNode. Node: 1. 若有inter

Dylan_Java_NYC的博客 512

【CASS精品教程】013:CASS9.1生成标准图幅案例教程

在CASS中,可以很方便的生成标准图幅,如50*50。本文演示cass中,根据测区范围标准图幅生成过程。

智慧空间实验室 1万+

PDF格式分析(一)简介

概述 PDF文件是一种编程形式的文档格式,它所有显示的内容,都是通过相应的操作符进行绘制的。 PDF基本显示单元包括:文字,图片,矢量图,图片 PDF扩展单元包括:水印,电子署名,注释,表单,多媒体,3D PDF动作单元:书签,超链接(初学者可以简单这么理解,对于研究比较深入的人员来说,拥有动作的单元有很多个,包括电子署名,多媒体,3D等等) 优势 一致性: 在所有可以打开PDF的机...

steve_cui的博客 2万+

LeetCode 160 :Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists:  A: a1 → a2 ↘

哈哈的个人专栏 2408

基于matlab的主成分分析的人脸二维码识别系统

人脸识别因其在系统安全验证、信用验证、刑侦跟踪、身份管理、视频会议、人机交互、智能家居等方面的巨大应用前景,成为当前模式识别和人工智能领域越来越热门的一个研究方向。随着安全入口控制和二维码智能扫描应用需求的快速增长,基于二维码识别的生物人脸统计识别技术也引起了人们的重视。本案例将详细讲解基于主成分分析的人脸特征提取的原理与方法,并将其与 QR 二维码的编解码进行结合,将 MATLAB 作为工具平台,调用 QR 二维码编解码应用程序,进而实现一个人脸二维码自动识别的系统原型。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 987

LeetCode-Intersection of Two Linked Lists

LeetCode Java Intersection of Two Linked Lists

坟头草一米七五 356

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

LeetCode -- Intersection of Two Linked Lists

LeetCode -- Intersection of Two Linked Lists

我的英文站点:https://iorilan.medium.com/ 1237

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode160. Intersection of Two Linked Lists

【代码】LeetCode160. Intersection of Two Linked Lists。

叶卡捷琳堡的博客 1422

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

leetcode 160. Intersection of Two Linked Lists python

leetcode 160. Intersection of Two Linked Lists python题目解法1:brutal force解法2:使用栈解法3:双指针法解法4:利用hashmap的思想 题目 Write a program to find the node at which the intersection of two singly linked lists begins. ...

qq_37821701的博客 505

[leetcode]Intersection of Two Linked Lists

Intersection of Two Linked Lists   Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1

不积跬步无以至千里 362

【leetcode 两个链表的交集点】Intersection of Two Linked Lists

leetcode上最新的面试题目,求两个链表的交集,难度为easy,附个人理解解析以及题目作者的英文解析。

wepon的专栏 1万+

Leetcode Intersection of Two Linked Lists 数组存栈的操作,栈的使用

Leetcode 160题 Intersection of Two Linked Lists Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: begin to inte...

润泽的博客 226

Leetcode 160. Intersection of Two Linked Lists

思路1: brute force。非常简单nested loop,遍历两个链表,找到第一个相同的node。时间复杂度n^2,空间复杂度1。 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } .

GoodJobJasper的博客 293

Leetcode之Intersection of Two Linked Lists

题目: Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: begin to intersect at node c1. Example 1: In...

qq_35455503的博客 184

【Leetcode】Intersection of Two Linked Lists

一原题 Intersection of Two Linked Lists   Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A:

DR_TITI的专栏 620

【leetcode c++】160 Intersection of Two Linked Lists

Intersection of Two Linked Lists   Write a program to find the node at whichthe intersection of two singly linked lists begins. For example, the following two linkedlists: begin to intersect

lif的博客 599

LeetCode 160之Intersection of Two Linked Lists 的Java题解

题目: Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘

u012249528的专栏 898
上一篇: LeetCode——Min Stack
下一篇: LeetCode——Majority Element
Seazzy5461
博客等级 码龄14年 8粉丝 66原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值