twosum
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 *ans = malloc(sizeof(int)*2);
for(int i=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
if(target == (nums[i] + nums[j]) && i!=j ){
ans[0] = i,ans[1] = j;
return ans;
}
}
}
return ans;
}
學習目的:
c++ define:
void* malloc (size_t size);
//example
int *data = malloc(1000, sizeof(int)); //宣告
free(data); //釋放
測試程式:
//測試程式
int* twoSum(int* nums, int numsSize, int target){
int *ans = malloc(sizeof(int)*2);
for(int i=0;i<numsSize;i++){
for(int j=0;j<numsSize;j++){
if(target == (nums[i] + nums[j]) && i!=j ){
ans[0] = i,ans[1] = j;
return ans;
}
}
}
return ans;
}
int main(){
int nums[] = {2, 7, 11, 15};
int target = 9;
printf("sizeof(nums) = %1lu \n", sizeof(nums)/sizeof(int));
int *out = twoSum(nums, sizeof(nums)/sizeof(int), target);
printf("\n%d\n",out[0]);
printf("%d\n",out[1]);
return 0;
}
