1. 程式人生 > >leetcode兩數之和C和python3

leetcode兩數之和C和python3

C:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */


int* twoSum(int* nums, int numsSize, int target) {
    int i,j,num = 0;
    int *buf = (int *)malloc(sizeof(int) * 1000);
    
    for(i = 0;i < numsSize;i++){
        for(j = i+1; j < numsSize;j++){
            if(nums[i] + nums[j] == target){
                buf[num++] = i;
                buf[num++] = j;
                return buf;
            }
        }
  
    }
    buf[num] = "\0";
    return buf;
    
}

python:

class Solution:
    rList = []
    def twoSum(self, nums, target):
        rList = []
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for indexa, numa in enumerate(nums):
            
            for indexb, numb in enumerate(nums):
                if indexa != indexb:
             
                    if numa + numb == target:
                        rList.append(indexa)
                        rList.append(indexb)
                        return rList
                    else:
                        continue
List = [3,4,6,8]
test = Solution()
test.twoSum(List, 10)