題目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize=2;
int *ret=(int*)malloc(2*sizeof(int)),i,j,temp;
for(i=0;i<numsSize;i++){
temp=target-nums[i];
for(j=i+1;j<numsSize;j++){
if(temp==nums[j]){
ret[0]=i;
ret[1]=j;
return ret;
}
}
}
return ret;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int max=nums[0],min=nums[0],i;
for(i=1;i<numsSize;i++){
max=max>nums[i]?max:nums[i];
min=min<nums[i]?min:nums[i];
}
int arrsize=max-min+1;
int *HT=calloc(arrsize--,sizeof(int));
HT[nums[0]-min]=-1;
for(i=1;i<numsSize;i++){
HT[nums[i]-min]=i;
}
*returnSize=2;
int *ret=(int*) malloc(2*sizeof(int)),index2;
for(i=0;i<numsSize;i++){
index2=target-nums[i]-min;
if(index2<0||index2>arrsize)continue;
if(HT[index2]){
ret[0]=i;
ret[1]=HT[index2];
if(HT[index2]<0)ret[1]=0;
if(ret[0]==ret[1]){
continue;
}
free(HT);
return ret;
}
}
return 0;
}
思路:
有offset方便存取值 e.g. -25不能找arr[-25] ,
但是可以找arr[-25-offset] (offset=min 故-25-offset會變正值)
index=0額外記錄成-1,因為calloc初始化陣列全部值都=0,
不設-1看不出0是初始化的0還是index的0
target-a-offset要做判斷 <0 或者 >max-min+1(Hash Table的Size) 都要跳過
因為array不能存取負index以及不能存取範圍以外。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dct = {}
for i,v in enumerate(nums):
if target-v in dct :
return [dct[target-v],i]
dct[v]=i
Runtime: 44 ms, faster than 85.74% of Python3 online submissions for Two Sum.
Memory Usage: 14.6 MB, less than 13.08% of Python3 online submissions for Two Sum.