LeetCode

1. Two Sum - brute-force with C

sheep_bell_door_ 2024. 3. 26. 14:22

1. Two Sum

 Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

> Integer list를 받아 두 수의 합으로 target을 만들 수 있는지 확인하는 문제이다.

Example 1:

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6

Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6

Output: [0,1]

Constraints:

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9

Code

Skeleton

  • 인자로 nums list의 주소, list의 크기, 목표 숫자, return list의 크기를 담을 변수의 주소를 받는다.
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    
}

Submission

  • Brute-force 방식을 사용하여 코드를 작성하였다.
  • result의 크기는 static하게 sizeof(int) * 2로 설정하였으며 이중 for문을 통해 target 숫자를 만들 수 있는지 확인하였다.
  • 없으면 NULL을 return하였다.
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int*    result;

    result = (int*)malloc(sizeof(int) * 2);
    // nullguard
    // if (!result)
    //     return 0;
    
    // Initialize result array
    result[0] = 0;
    result[1] = 0;

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

Submission Detail

  • Runtime: 147 ms
  • Memory Usage: 6.5 MB

Accepted Solutions Runtime Distribution

Accepted Solutions Memory Distribution