大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
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.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
首先先簡單的翻譯一下題目
給一個陣列與一個目標值,可以從陣列中找到兩個值相加等於目標值,要回傳的內容則是這兩個值在陣列中的位址。
這邊題目是假設剛好只會有一個解,且相同的元素不能用第二次,但看到Example3
的測資,我想題目應該是指在陣列中每個位址的元素只能被使用一次。
第一個想法就是暴力解 (゚∀゚),有想到其他的再改~
作法大致上是這樣
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
remain = 0
for num1 in range(len(nums)):
remain = target - nums[num1]
for num2 in range(num1+1, len(nums)):
if remain == nums[num2]:
return [num1,num2]
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int *indices = (int*)malloc(sizeof(int)*2);
bzero(indices , sizeof(int)*2);
int remain = 0;
for (int num1=0 ; num1<numsSize-1 ; num1++){
remain = target - nums[num1];
indices[0] = num1;
for (int num2=num1+1 ; num2<numsSize ; num2++){
// printf("%d: %d, %d: %d :=: %d\n", num1, nums[num1], num2, nums[num2], remain);
if (remain == nums[num2]){
indices[1] = num2;
remain = 0;
break;
}
}
if (remain == 0)
break;
}
*returnSize = 2;
return indices;
}
Python
C
大家明天見