2015年7月28日 星期二

LEET code-Two Sum

Two Sum

 Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
反正就是找出哪兩個加起來會是target
又只會有一組  就直接找
概念是
先sort一遍  從小排到大
兩個指標left and right
從數列的最開頭跟最尾端開始
left=nums[0]
right=nums[numsSize-1]
如過left+right > target
因為已經排列過 所以可以確定是right太大
讓她往左一一格
left+right < target
就是left 太小   向右一格

找到答案放到ANS陣列
因為答案要求的是要沒經過排序過的  所以要把原始位置再找出來


PS: 這邊用SyntaxHighlighter 會奇怪字元出現,懶得找BUG


int compare(const void *arg1, const void *arg2) {
  int compare(const void *arg1, const void *arg2) {
  return  (*(int *)arg1 - *(int *)arg2);
}
int* twoSum(int* nums, int numsSize, int target) {

    
    
    int* ans= (int *)malloc(sizeof(int)*2);
    int* temp = (int *)malloc(sizeof(int)*numsSize);
    memcpy(temp,nums,numsSize*sizeof(int));
    qsort( (void*)temp, numsSize, sizeof(int) ,compare) ;
    int find=0;
    int left=0;
    int right=numsSize-1;
    while(left
        if(temp[left]+temp[right]   >target){
            right--;
        }else if(temp[left]+temp[right]< target){
            left++;
        }else {
            ans[0]=temp[left];
            ans[1]=temp[right];
           // ans[0]=10;
            break;
        }
        
    }
    //ans[0]=10;
    
    int flag=0;
    for(int i=0;i
        if(ans[0]==nums[i]){
            ans[0]=i+1;
            flag++;
        }
        else if(ans[1]==nums[i] ){
            ans[1]=i+1;
            flag++;
        }
        if(flag>=2){
            if(ans[0]>ans[1]){
                int temp=ans[1];
                ans[1]=ans[0];
                ans[0]=temp;
            }
            break;
        }
    }
    
    free(temp);
    return ans;
}



沒有留言:

張貼留言