LeetCode两数之和

时间:2024-07-18 13:59:00

C

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    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;
}

Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        for i in range(n):
            for j in range(i+1 ,n):
                if nums[i] + nums[j] == target:
                    return [i,j]

        return []