leetcode 001--Two Sum

problem:

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].
Difficulty:Easy

hint1:

  • 非有序表,采用折半查找出錯(cuò)
  • 返回指針值的函數(shù)返回?cái)?shù)組會(huì)出錯(cuò)

采用暴力破解法,窮舉所有的數(shù),時(shí)間復(fù)雜度為O(n^2)

code:

#include<stdio.h> 
#include<malloc.h>
int* twoSum(int*nums,int numsSize,int target){
    int *arr = (int*)malloc(2*sizeof(int)),i,j;
    for(i =0;i<numsSize;i++){
        for(j =i+1;j<numsSize;j++){
            if(nums[i]+nums[j]==target){
                arr[0]=i;
                arr[1]=j;
            }
        }
    }
    return arr;
}
int main(){
    int arr[3] = {2,3,4};
    int target = 6;
    int a[2];
    int *index = a;
    index = twoSum(arr,3,target);
    printf("%d....%d",index[0],index[1]);
}

hint2:

采用用hash存儲(chǔ),空間換時(shí)間,最終時(shí)間復(fù)雜度為O(n)

int* twoSum(int*nums,int numsSize,int target){
    int min,max,len,i;
    int *arr = (int*)malloc(2*sizeof(int));
    min = nums[0];
    for(i = 1;i < numsSize;i++){
        if(min > nums[i]){
            min = nums[i];        //獲取輸入數(shù)組中最大的數(shù)值用以確定hash表的頭部位置
        }
    }
    max = target - min;     //計(jì)算出可能得到的符合條件的最大數(shù)  
    len = max - min + 1;      //len代表可能取到的最大的數(shù) 
    int *h = (int*)malloc(len*sizeof(int));
    
    for(i = 0;i<len;i++){
        h[i]=-1;                //初始化hash表
    }
    for(i = 0;i<numsSize;i++) {
        if(nums[i]-min<len){
            if(h[target-nums[i]-min] != -1){
                arr[0] = h[target-nums[i]-min];
                arr[1] = i;
                return arr;
            }
            h[nums[i]-min] = i;     //若未找到則存儲(chǔ)進(jìn)hash表中
        }
    }
    free(h);
    return arr;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容