LeeCode(1) two sum C语言 C++版本

    xiaoxiao2022-07-12  145

    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, and you may not use the same element twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]

    c++版本

    class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; for(int i =0;i<nums.size()-1;i++) { int temp = target - nums[i]; for(int j = i+1 ; j<nums.size();j++) { if(nums[j] == temp) { result.push_back(i); result.push_back(j); return result; } } } return result; } };

    c语言版本

    int* twoSum(int* nums, int numsSize, int target, int* returnSize){

    int i =0; int j =0; *returnSize = 2; int * result =NULL; for(i=0;i<numsSize-1;i++) { int temp = target - nums[i]; for(j = i+1 ; j<numsSize;j++) { if(nums[j] == temp) { result = (int*)malloc(sizeof(int) * 2); result[0] = i; result[1] = j; return result; } } } return result;

    }

    最新回复(0)