고양이와 코딩
[LeetCode] Two Sum 본문
728x90
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.
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 <= 104
- -109 <= nums[i] <= 109
- -109 <= target <= 109
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
Solution
#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int* results = (int*)malloc(2 * sizeof(int));
*returnSize = 2;
for (int i = 0; i < numsSize; i++) {
for (int j = i + 1; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
results[0] = i;
results[1] = j;
return results;
}
}
}
return NULL;
}
nums배열, nums의 length를 의미하는 numsSize, 배열에서 더해서 나올 수 있는 값을 의미하는 target
그리고 반환되는 배열의 크기를 알려주기 위해 returnSize에 크기 2를 할당한다.
'C' 카테고리의 다른 글
[LeetCode] Roman to Integer (1) | 2024.11.10 |
---|---|
[LeetCode] Palindrom number (0) | 2024.11.10 |
함수 포인터 연습문제 (0) | 2024.06.16 |
포인터 진짜 짜증남 (0) | 2024.06.15 |
function (1) | 2024.06.09 |