leetcode刷题--基础数组--两数之和(C)待补充

  1. 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
    示例:
    给定 nums = [2, 7, 11, 15], target = 9
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

思想:(1)暴力解法,直接从数组开始访问到数组结束。由于python的语法不是特别熟悉,不知道有哪些可用的包或者函数,所以写的很是生涩,当然效率也很低。

// 时间复杂度O(n^2)
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        twoSum = []
        for i in range(0, len(nums)):
            a = target - nums[i]
            for j in range(i+1, len(nums)):
                if(a == nums[j]):
                    twoSum.append(i)
                    twoSum.append(j)
        return twoSum
                    
//同样的思想用C
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int *twoSum = (int *)malloc(sizeof(int)*2);
    int temp;
    for(int i=0;i<numsSize;i++){
        temp = target - nums[i];
        for(int j=i+1;j<numsSize;j++){
            if(temp == nums[j]){
                twoSum[0]=i;
                twoSum[1]=j;
                return twoSum;
            }
        }
    }
    return 0;
}

  1. 这个题目提升一下,变成是三个数之和。题目描述如下:给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
    注意事项:在三元组(a, b, c),要求a <= b <= c。结果不能包含重复的三元组。
    样例
    如S = {-1 0 1 2 -1 -4}, target = 0
    你需要返回的三元组集合的是:(-1, 0, 1), (-1, -1, 2)

思路:(1) 首先,将数组按从小到大的排序,然后从头挑选一个元素,接着使用首尾两个指针来挑选后两个元素。[略]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值