1.Two Sum

2018-11-30  本文已影响7人  faterman

问题:

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.

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

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

实现:

#include <stdio.h>
#include <stdlib.h>

int* twoSum(int* nums, int numsSize, int target);
void reverseArray(int *nums, int numsSize);

int main(int argc, const char * argv[]) {
    int nums[5] = {-1,-2,-3,-4,-5};
    
    int *result = twoSum(nums, 5, -8);
    reverseArray(result, 2);
    
    return 0;
}

int* twoSum(int* nums, int numsSize, int target) {
    static int indices[2];
    for (int i = 0; i < numsSize; i++) {
        for (int j = 0; j < numsSize; j++) {
            if (target == nums[i] + nums[j] && i != j) {
                indices[0] = i;
                indices[1] = j;
                return indices;
            }
        }
    }
    return indices;
}

void reverseArray(int *nums, int numsSize) {
    printf("[");
    for (int i = 0; i < numsSize; i++) {
        if (numsSize - 1 == i) {
            printf("%d",nums[i]);
        }else {
            printf("%d,",nums[i]);
        }
    }
    printf("]\n");
}
上一篇下一篇

猜你喜欢

热点阅读