两个数相加(c语言)

1./给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target

// 的那 两个 整数,并返回它们的数组下标。
//你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。你可以按任意顺序返回答案。
//示例 1:
//输入:nums = 2, 7, 11, 15, target = 9
//输出:0, 1
//解释:因为 nums0 + nums1 == 9 ,返回0, 1
//示例 2:
//输入:nums = 3, 2, 4, target = 6
//输出:1, 2
//示例 3:
//输入:nums = 3, 3, target = 6
//输出:0, 1

2.我们判断相邻的数字与target的是否相等,如果相等ret0=i,ret1=j return ret, *returnSize=2;反之没有一个相等则*returnSize=0,返回NULL。(注意:ret要一个二个int的空间)

cs 复制代码
#include<stdio.h>
#include<stdlib.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    int j = 0;;
    for (int i = 0; i < numsSize; i++)
    {

        for (int j = i + 1; j < numsSize; j++)
        {
            if (nums[i] + nums[j] == target)
            {
                int* ret = malloc(sizeof(int) * 2);
                ret[0] = i;
                ret[1] = j;
                *returnSize = 2;
                return ret;
            }
        }
    }
    *returnSize = 0;
    return NULL;
}
int main()
{
    int nums[10] = {"2,7,11,15"};
    int numsSize = strlen(nums);
    int target = 0;
    scanf_s("%d", &target);
    int returnSize = 0;
    int*dev=twoSum(nums, numsSize, target, &returnSize);
    for (int i = 0; i < returnSize; i++)
    {
        printf("%d ", dev[i]);
    }
    return 0;
}
相关推荐
JieE21214 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack201 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树1 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050732 天前
(一)小红的数组操作
算法·编程语言
怕浪猫2 天前
Electron 系列文章封面图
算法·架构·前端框架