LeetCode001 Two Sum C语言

本文介绍LeetCode上经典题目“两数之和”的解决方案。通过双重循环遍历整型数组找到两个数,使其和等于指定目标值,并返回这两个数的下标。文章还讨论了该算法的时间复杂度,并提及了利用哈希表提高效率的可能性。
1
2
3
4
5
6
7
8
9
10
11
12
1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [271115], target = 9,
 
Because nums[0] + nums[1] = 2 7 9,
return [01].
 
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
 
Subscribe to see which companies asked this questio
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int i,j;
    int *a = (int *)malloc(sizeof(int) * 2);
    for(i=0;i<numsSize;i++){
        for(j=i+1;j<numsSize;j++){
            if(nums[i]+nums[j]==target){
                a[0]=i;
                a[1]=j;
                break;
            }
        }
    }
    //printf("%d",a[1]);
    return a;
}

LeetCode第一题!!!!没想到两层循环就解决了,想想还有点激动。看了网上才知道这样

时间复杂度O(N*2)。

好像快点的话还可以hash表?

有机会再说吧[%>_<%]


本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1864612


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值