LeetCode //C - 1. Two Sum
2023-12-13 21:41:20
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.
?
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 < = n u m s . l e n g t h < = 1 0 4 2 <= nums.length <= 10^4 2<=nums.length<=104
- ? 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 ?109<=nums[i]<=109
- ? 1 0 9 < = t a r g e t < = 1 0 9 -10^9 <= target <= 10^9 ?109<=target<=109
- Only one valid answer exists.
From: LeetCode
Link: 1. Two Sum
Solution:
Ideas:
In this implementation, we loop through each element and then loop through the rest of the elements to find a pair that sums up to the target. Once the pair is found, we store their indices in the result array and return it.
Code:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int* result = malloc(2 * sizeof(int)); // Allocate memory for the result
*returnSize = 2; // Set the return size to 2
for (int i = 0; i < numsSize - 1; i++) {
for (int j = i + 1; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
// In case no solution is found, though the problem statement guarantees one solution
result[0] = -1;
result[1] = -1;
return result;
}
文章来源:https://blog.csdn.net/navicheung/article/details/134912412
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!