[Written test question] Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target, and return their array subscripts.

Method: Brutal enumeration


Ideas and algorithms

The easiest way to think of is to enumerate each number x in the array and find whether target - x exists in the array.

When we look for target - x by traversing the entire array, we need to note that every element before x has already matched x, so there is no need to match again. Each element cannot be used twice, so we only need to find target - x in the element after x.

Complexity analysis

Time complexity: O(N^2)

Space complexity: O(1)

Code

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;
}

Guess you like

Origin blog.csdn.net/2301_78131481/article/details/134034493