您的位置:首页 > 其它

Leetcode习题记录——Two Sum

2017-07-07 14:52 411 查看
题目: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.

方法一:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int *a = (int*)malloc(2*sizeof(int));
for(int i = 0 ; i < numsSize ; i++ ){
for (int j = i + 1 ; j < numsSize ; j++){
if( nums[i] + nums[j] == target){
a[0] = nums[i];
a[1] = nums[j];
}
}
}
return a;
}


这里是第一种对简单的解法,两次循环遍历所有的组合。思路很简单,值得一提的是这个malloc的用法:malloc (size_type size)

返回的必须是一个指针,此函数包含于 stdlib.h

方法二:

int compare(const void *a , const void *b){
return *(int*) a - *(int*) b;
}

int* twoSum(int* nums, int numsSize, int target) {
bool flag = true;
int* result = malloc(sizeof(int) * 2);
int* temp = malloc(sizeof(int) * numsSize);
qsort(nums,numsSize,sizeof(int),compare);
int low = 0;
int high = numsSize-1;
for (int i = 0; i < numsSize; i++){
if(nums[low] + nums[high] > target)
high--;
if(nums[low] + nums[high] < target)
low++;
if(nums[low] + nums[high] == target)
break;
}
result[0] = nums[low];
result[1] = nums[high];
return result;
}


这里是第二种做法,思路很简单,先将数组排序,设置两个指针一个指向最小值,一个指向最大值,将这两个数相加,如果超过target,那么说明大的数太大,所以最高的指针向下移动一个,指向一个稍微小一点的数,如果低于target,同理。排序的函数也不用自己写,在库中有,qsort( void *base, size_t num, size_t width, int (cdecl *compare )如何使用这个函数具体详见:http://blog.csdn.net/yuanjilai/article/details/7348345
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: