LeetCode::Two Sum C语言

该博客介绍了如何使用C语言解决LeetCode上的两数之和问题。博主首先提供了效率较低的双重循环解法,然后详细解释并展示了利用哈希表实现的O(n)时间复杂度解决方案,这种方法显著提高了代码运行速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解答方法一:双重循环尝试, 复杂度O(n^2)

#include<stdio.h>

#include<stdlib.h>
int *twoSum(int numbers[], int n, int target)
{
  
  
    if ((numbers == NULL)|(n < 2))
    {
  
  
        return NULL;
    }
    int index1;
    int index2;
    int* ret = (int*)malloc(sizeof(int)*2);
    for (index1 = 0; index1 < n; ++index1)
    {
  
  
        for (index2 = index1 + 1; index2 < n; ++index2)
        {
  
  
            int sum_tmp = numbers[index1] + numbers[index2];
            if (sum_tmp == target)
            {
  
  
                ret[0] = index1 + 1;
                ret[1] = index2 + 1;
                return ret;
            }
        }
    }
    return NULL;
}
int main(int argc, char **argv)
{
  
  
    int array[] = {
  
  2, 7, 11, 15};
    size_t n = sizeof(array)/sizeof(int);
    int target = 9;
    int* result = twoSum(array, (int)n, target);
    printf("The index1: %d; the index2: %d\n", result[0], result[1]);
    free(result);//memory deallocation
}
点评:

解法非常直观, 但是复杂度O(n^2),所以效率很差,在leetcode上无法通过: Submission Result:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值