LeetCode (力扣) 15. 3Sum (C) - Medium ( 排序+搜寻法 )

详解力扣中int *returnSize和int **returnColumnSizes 在用C语言刷力扣的时候,我们经常会看到这两个东西,int* returnSize 和 int** returnColumnSizes。连题目都看不懂,更何况是做题呢?我也是查找了网上零零碎碎的资料和做了蛮多题之后,终于想明白了。遂整理成此文,希望能帮到后来者。个人理解,如有不足,烦请斧正。 首先我们来看一道题,力扣的第 15 题,三数之和。这是笔者第一次接触到这两个东西的题目。 三数之和 题干: 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + . 阅读详情

同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。

题目为给定一串数字,输出所有三个数字相加为 0 的数字组合。

这题有速度的问题,建议使用排序与搜寻方法。

 

题目与范例如下

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:

Input: nums = []
Output: []
Example 3:

Input: nums = [0]
Output: []

Constraints:

0 <= nums.length <= 3000
-105 <= nums[i] <= 105


解题策略为先排序,这样在 for 回圈时能跳过三个都是正整数的组合。

我采用的排序法是 merge sort , sortsub是用于 merge sort 的递归函式。

程式碼中採用了兩層的 for 第一層控制第一個數字 ( i ), 從 0 ~ ( n - 3 ) , for 的第二層控制第二個數字 ( j ), 從 ( i + 1 ) ~ ( n - 2 ) ,第三個數字透過搜尋法尋找,我採用的是二元搜尋法。

依序输出找到的数字组合。

 

下方为我的代码

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

void mergeSort(int* num, int numsSize);
void sortsub(int* num, int low, int high);
void merge(int* num, int low, int middleL, int middleR, int high);
bool binarySearch(int* nums, int left, int right, int target);

int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
    
    
    *returnSize = 0;            // number of return pairs
    int step = 512;              // each memory alloc
    *returnColumnSizes = (int*)malloc(sizeof(int*)*step); 
    int** re = (int**)malloc(sizeof(int*)*step);

    
    mergeSort(nums, numsSize);

    for(int i = 0; i<numsSize-2 ; i++){
        if(i!=0){                               //Jump Same num
            while(i<numsSize-2){
                if(nums[i]==nums[i-1])
                    i++;
                else
                    break;
            }
        }
        if(i<numsSize-2){
            for(int j = i+1; j<numsSize-1 ; j++ ){
                if(j!=i+1){                               //Jump Same num
                    while(j<numsSize-1){
                        if(nums[j]==nums[j-1])
                            j++;
                        else
                            break;
                    }
                }
                if(j<numsSize-1){
                    if(binarySearch(nums,j+1,numsSize-1,((nums[i]+nums[j])*(-1)))){
                        if((*returnSize) != 0 && (*returnSize)%step == 0){            // Create space
                            *returnColumnSizes = (int*)realloc(*returnColumnSizes, sizeof(int*) * ((*returnSize)+step));
                            re = (int**)realloc(re, sizeof(int*) * ((*returnSize)+step));
                        }

                        (*returnColumnSizes)[*returnSize] = 3;
                        re[*returnSize] = (int*)malloc(sizeof(int)*3);
                        re[*returnSize][0] = nums[i];
                        re[*returnSize][1] = nums[j];
                        re[*returnSize][2] = 0-nums[i]-nums[j];
                        (*returnSize)++;               
                    }
                }
            }
        }
    }
   
    return re;
}


void mergeSort(int* num, int numsSize) {
    sortsub(num, 0, numsSize - 1);
}

void sortsub(int* num, int low, int high) {
    if ((high - low) >= 1) {
        int middleL = (low + high) / 2;
        int middleR = middleL + 1;
        sortsub(num, low, middleL);
        sortsub(num, middleR, high);
        merge(num,low,middleL,middleR,high);
    }

}

void merge(int *num,int low,int middleL,int middleR, int high) {
    int combinedIndex = 0, leftIndex = low, rightIndex = middleR;
    int* tempArray = (int*)malloc(sizeof(int) * (high - low + 1));

    while (leftIndex <= middleL && rightIndex <= high) {
        if (num[leftIndex] < num[rightIndex]) {
            tempArray[combinedIndex++] = num[leftIndex++];
        }
        else
            tempArray[combinedIndex++] = num[rightIndex++];    
    }

    if (leftIndex > middleL) {
        while (rightIndex <= high) {
            tempArray[combinedIndex++] = num[rightIndex++];
        }
    }
    else {
        while (leftIndex <= middleL) {
            tempArray[combinedIndex++] = num[leftIndex++];
        }
    }

    for (int i = low; i <= high; i++) {
        num[i] = tempArray[i - low];
    }
}

bool binarySearch(int* nums, int left, int right, int target) {
    int middle;
    if (target < nums[left] || target > nums[right])
        return false;
    while (left <= right) {
        middle = (right + left) / 2;
        if (nums[middle] == target) {
            return true;
        }
        else if (target > nums[middle]) {
            left = middle + 1;
        }
        else {
            right = middle - 1;
        }
    }
    return false;
}

 

下方为时间与空间之消耗

Runtime: 216 ms, faster than 25 % of C online submissions for Roman to Integer.

Memory Usage: 36.3 MB, less than 20.51 % of C online submissions for Roman to Integer.

( 本题一次配置的记忆体空间尽量大一点,太小需要多次配置记忆体会大幅提升执行的时间。 )

逆向工程实战:从零解析微信PC版协议,并用开源代码构建你的私有化接口 本文详细解析了微信PC版的通信协议架构,从逆向工程基础到网络流量捕获、关键函数定位与HOOK技术实践,最终通过开源代码构建私有化接口。文章重点介绍了协议特征分析、HOOK技术应用以及安全实践,帮助开发者深入理解企业级通信协议的设计逻辑和安全机制。 阅读详情

相关推荐

TI AWR2944毫米波雷达开发板开箱:用官方Demo快速上手3D点云与热图生成

本文详细介绍了TI AWR2944毫米波雷达开发板的开箱与实战应用,包括硬件准备、软件开发环境搭建、Demo固件刷写与配置、实时可视化与数据解析等全流程指南。通过官方Demo快速上手3D点云与热图生成,帮助开发者高效掌握毫米波雷达技术在工业检测、智能交通等领域的应用。

weixin_42627853的博客 308

Leetcode中的returnColumnsizes到底是什么?

最近刷一些二维数组的题,对 int** generate(int numRows, int* returnSize, int** returnColumnSizes) 这种东西的传参感到非常迷惑 那么returnColumnSizes是什么? 是一个一维数组的地址的地址。(地址即指针) return-Column-Sizes,类似于returnSize,是一个“返回值”,返回的信息是二维数组的列数。 returnSize中要返回的信息是二维数组的行数。 为什么传入的参数是retur..

qq_41975735的博客 4853

通讯模块_三菱IQ-R PLC串口通讯模块RJ71C24进行Modbus-RTU通讯

在日常的选型中,很多电气工程师咨询我,三菱iQ-R系列有没有Modbus通讯模块,我在这里可以肯定的回复您,这个肯定是有的;我们共有三种可以选择分别是RJ71C24、RJ71C24-R2、RJ71C24-R4。RJ71C24系列支持MC协议通信、通信协议通信、无顺序协议通信、双向协议通信全、MODBUS通信。当我帮助他们选型之后,他们在使用的时候,又是一头雾水。那么今天我抽一些时间讲解一RJ71...

weixin_39878549的博客 9269

妙语趣说 - Leetcode中的returnColumnsizes为何物?

”什么?你说穿上就不端庄典雅了?" 连珠妙语,一套骚话让你想不到。

AuthurLEE's Blogs 6539

python知网爬虫论文pdf下载+立即可用(动态爬虫)

python实现动态爬虫知网论文,搜索+自动翻页+下载 收集数据利器

Braylon的博客 5379

【华为OD机试】2024年真题C卷(python)-API集群负载统计

【华为OD机试】-API集群负载统计-【华为OD机试】-API集群负载统计:某个产品的 restful API 集合部署在服务器集群的多个节点上,近期对客户端访问日志进行了采集,需要统计各个API的访问频次,根据热点信息在服务器节点之间做负载均衡,现在需要实现热点信息统计查询功能。 restful API 是由多个层级构成,层级之间使用/连接,如 A/B/C/D 这个地址,A属于第一级,B属于第二级,C属于第三级,D属于第四级。 现在负载均衡模块需要知道给定层级上某个名字出现的频次,未出现过用0

u014481728的博客 1491

关于leetcode上*returnSize 与 *returnColumnSizes的实际意义及使用

个人整理学习用,有错误欢迎指正 目录出现环境实际意义returnSizereturnColumnSizes使用 出现环境 在leetcode的题目中,当使用C语言求解涉及二级指针的题目,或者需要输出类似于{[1,2,3],[2,3,4],...}这种不止一个数组的结果是,经常看到形如int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {...}的函数调用格式。先上结论:int* returnSiz

weixin_45695709的博客 1万+

uniapp - 超详细实现播放 svg / svga 格式动画组件插件,用于直播间赠送礼物特效动画或项目动画特效较多的应用(新手小白保姆级教程,提供插件+详细运行示例+使用文档+注意事项+格式说明)

uniappsvga,uniapp播放svga动画,uniapp中使用svga动画详细教程,uniapp播放svga的插件,uniapp有没有调用svga格式动画的组件插件,uinappH5App小程序全端兼容的svga播放器免费好用插件,uniapp好用的svga格式动画插件,在uniapp中使用SVGAPlayer播放svga动画,uniapp中使用svga动画,编译到apph5,uniapp运行svg动画,uniapp怎么使用svga文件格式,uniapp播放svg格式的动画教程,un

🏆 前端领域优质创作者 1万+

《Leetcode零基础刷题指南》- 二级指针

前言 常见二级指针不再赘述,主要是在力扣中二级指针的应用,难度较大,反复推敲。 一、二级指针参数介绍(刷题) int** func(int** matrix, int matrixSize, int* matrixColSize, int* returnSize, int** returnColumnSizes){ } 参数名 变量类型 实际含义 matrix 二级指针 传入的矩阵首地址 matrixSize 普通变量 ...

YQ20210216的博客 1247

100天精通Python(爬虫篇)——第118天:selenium自动化操作浏览器基础大总结

一、Selenium框架环境搭建 1. 下载模块 2. 安装浏览器驱动WebDriver 二、基础操作 1. 打开浏览器 2. 无界面模式 3. 元素定位 4. 元素操作 5. 前进后退 6. 执行js 7.页面等待 隐式等待(常用) 显式等待(了解) 三、进阶操作 1. 使用代理ip 2. 修改请求头 3. 隐藏指纹特征.....................

努力让自己发光,对的人才能迎着光而来 10万+

cartographer运行错误集合

播放bag的时候错误 Check failed: sensor_to_tracking->translation().norm() < 1e-5 The IMU frame must be colocated with the tracking frame. Transforming linear acceleration into the tracking frame will otherwise be imprecise tracking frame不是imu的link 修改lua文件中的.

Studying…… 2020

15. 3 Sum (C,Python)

本文讲述了Array类中第15个问题的几种解法,实现语言包括C,Python, 难度为medium。 问题: Given an arraynumsofnintegers, are there elementsa,b,cinnumssuch thata+b+c= 0? Find all unique triplets in the array which give...

魔法师の屋子★↓☆ 3495

如何使用freesurfer对T1w结构像进行分区指标的提取?——皮层面积,灰质体积,平均厚度,厚度标准差,平均曲率、高斯曲率、曲率指数、折叠指数

如何使用freesurfer对T1w结构像进行分区指标的提取?——皮层面积,灰质体积,平均厚度,厚度标准差,平均曲率、高斯曲率、曲率指数、折叠指数

从事脑科学核磁共振方法学研究,在Nature communications等权威期刊发表研究论文,熟练掌握磁共振处理方法和统计学方法,欢迎大家和我交流。 3787

Leetcode 15. 3Sum [medium][java]

3Sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not...

inkhk的博客 189

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

【LeetCode】LeetCode——第15题:3Sum

【LeetCode】LeetCode——第15题:3Sum

hujingshuang 6132

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

[LeetCode] 15.三数之和(Medium)C语言题解

题目 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 示例 ①示例1 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] ...

wjy的博客 1893

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

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

LeetCode OJ 15 3Sum [Medium]

题目描述: Given an array S of n integers, are there elements a, b,c in S such that a + b + c = 0? Find all unique triplets in the array whichgives the sum of zero. Note: The solution set must not cont

大吱的博客 381

LeetCode (力扣) 16. 3Sum Closest (C) - Medium 暴力解、双指标( Merge Sort )、双指标( Quick Sort )

同步发于JuzerTech网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。

JuzerTech的博客 240

Leetcode题medium11/15/16/18/31/33/34/39/40,Python多种解法(三)

前文   继上一篇:Leetcode题121/122/167/169/189/217/219/268/283,Python多种解法(二),这次开始分享数组medium的题,说实在的,到了中等题,很难自己过了,只有少部分和easy一样难度的题才能过,打击还是有的,不过还是继续刷吧,等二刷三刷的时候,相信自己的代码能力和算法能力应该会有提高的!那开始上题了! 11. Container With Mo...

weixin_42681866的博客 455

LeetCode 18. 4Sum

一 题目 Given an arraynumsofnintegers and an integertarget, are there elementsa,b,c, anddinnumssuch thata+b+c+d=target? Find all unique quadruplets in the array which gives the sum ...

bohu83的博客 200

LeetCode-15-3Sum(证明/KSum)-Medium

题目理解: 求解vector中三个数(a,b,c)之和为0,其中,a、b、c不能为重复值,并且按照a 解题分析: 1. 典型的KSum题目; 1)先排序; 2)首尾两端两个指针同时向对端移动; 3)过程中避免重复的结果; 题目的关键是证明两个指针向对端移动的过程中,不会漏掉有效的取值(可以使用反正法进行证明); 解题代码: class Solution { pub

eddy_liu的专栏 505

[LeetCode] 18.四数之和(Medium)C语言题解

题目 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 示例 ①示例1 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] ...

wjy的博客 597

【Leetcode】【Medium】4Sum

Given an arraySofnintegers, are there elementsa,b,c, anddinSsuch thata+b+c+d= target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a...

weixin_30443813的博客 94

java 3sum_LeetCode第[15]题(Java):3Sum (三数之和为目标值)——Medium

题目难度:Medium题目:Given an arraySofnintegers, are there elementsa,b,cinSsuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero.Note:The solution set must not...

weixin_36403838的博客 319

Leetcode 15 [medium]--3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain d

fawnzou2017的博客 210

LeetCode Index

一、数学问题 Easy 7. Reverse Integer [Easy] 172. Factorial Trailing Zeroes [Easy] 阶乘有几个0 263-264. Ugly Number I & II [Easy & Medium] 丑数系列 278. First Bad Version [Easy] 二分查找 509...

qq_35319215的博客 151
上一篇: LeetCode (力扣) 14. Longest Common Prefix (C) - Easy
下一篇: LeetCode (力扣) 16. 3Sum Closest (C) - Medium 暴力解、双指标( Merge Sort )、双指标( Quick Sort )
JuzerTech
博客等级 码龄6年 7粉丝 34原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值