以写作调身心

Leetcode-1-Two Sum

题目

two-sum

Golang

func twoSum(nums []int, target int) []int {
    var result = [2]int {0,0}
    if len(nums) < 2 {
        return nil
    }
    
    for i := 0 ; i < len(nums) - 1; i++ {
        for j := i + 1; j < len(nums); j++ {  
            if(nums[i] + nums[j] == target){
                result[0] = i
                result[1] = j
                return result[:]  //返回结果
            }
        }
    }
    return nil    
}

C

int* twoSum(int* nums, int numsSize, int target) {
    int *a = (int*)malloc(2 * sizeof(int));
    for(int i = 0;i < numsSize;i++){
        for(int j = i + 1;j < numsSize;j++){
            if(nums[j] == target - nums[i]){
                a[0] = i;
                a[1] = j;
            }
        }
    }

    return a;
}

评论