1、基礎方法
思路:雙層遍歷數(shù)組,如果找到目標的target芳悲,退出雙層循環(huán)
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int *result = (int *)malloc(2 * sizeof(int));
bool found = false;
for(int i = 0; i < numsSize - 1; i++){
if(!found){
for(int j = i + 1; j < numsSize; j++){
if(nums[i] + nums[j] == target){
result[0] = i;
result[1] = j;
found = true;
break;
}
}
}
}
if(found){
*returnSize = 2;
}
else{
*returnSize = 0;
}
return result;
}
2枪芒、字典方法
思路:
1、首先遍歷數(shù)組確定nums的最大值max和最小值min挺庞;
2晰赞、創(chuàng)建字典map數(shù)組,用于快速定位目標值在nums數(shù)組中的索引 选侨。map數(shù)組以數(shù)組下標為要找的目標元素掖鱼,下標對應的值為該下標在nums數(shù)組中的下標位置,例如map[3] = 5援制,即在數(shù)組nums中戏挡,元素3在nums中的下標為5。數(shù)組大小為max - min + 1晨仑,目的是為了將max - min + 1 區(qū)間所有元素存入map褐墅,由于nums并不是從min-max連續(xù)的,所以map會有許多為空元素寻歧。為了防止map數(shù)組初始化的時候數(shù)組元素隨機賦值掌栅,需要用到calloc函數(shù),將map的元素值均初始化為0码泛。
3猾封、遍歷nums數(shù)組,對于每一個數(shù)組元素nums[i]噪珊,如果map中存在lookfornum = target - nums[i]晌缘,則直接返回齐莲,如果不存在,則建立數(shù)組元素的地址映射磷箕,map[nums[i] - min] = i + 1(其中选酗,索引存為i + 1,而不是存為i本身岳枷,原因為當遍歷到數(shù)組最小值時芒填,即nums[i] - min = 0時,無法區(qū)分該索引到底是min在原nums數(shù)組中下標就是0空繁,還是因為map數(shù)組在calloc 函數(shù)初始化的時候為0)殿衰。
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i, max, min;
max = min = nums[0];
for(i = 0; i < numsSize; i++) {
if(nums[i] > max) max = nums[i];
if(nums[i] < min) min = nums[i];
}
int *map = (int *)calloc((max - min + 1), sizeof(int));
int *result = (int *)malloc(2 * sizeof(int));
bool found = false;
for(i = 0; i < numsSize; i++) {
int lookfornum = target - nums[i];
if(lookfornum < min || lookfornum > max) continue;
int dis = lookfornum - min;
if (map[dis]) {
result[0] = i;
result[1] = map[dis] - 1;
found = true;
break;
}
else{
map[nums[i] - min] = i + 1;
}
}
if(found)
*returnSize = 2;
else
*returnSize= 0;
return result;
}
本系列文章,旨在打造LeetCode題目解題方法盛泡,幫助和引導同學們開闊學習算法思路闷祥,由于個人能力和精力的局限性,也會參考其他網(wǎng)站的代碼和思路傲诵,如有侵權凯砍,請聯(lián)系本人刪除。