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.
这里是第一种对简单的解法,两次循环遍历所有的组合。思路很简单,值得一提的是这个malloc的用法:malloc (size_type size)
返回的必须是一个指针,此函数包含于 stdlib.h
方法二:
这里是第二种做法,思路很简单,先将数组排序,设置两个指针一个指向最小值,一个指向最大值,将这两个数相加,如果超过target,那么说明大的数太大,所以最高的指针向下移动一个,指向一个稍微小一点的数,如果低于target,同理。排序的函数也不用自己写,在库中有,qsort( void *base, size_t num, size_t width, int (cdecl *compare )如何使用这个函数具体详见:http://blog.csdn.net/yuanjilai/article/details/7348345
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
相关文章推荐
- leetcode刷题记录-Two Sum
- leetCode 刷题记录-1. Two Sum
- Leetcode习题: Two Sum
- leetcode刷题记录--Two Sum
- Python leetcode记录(1) -Two Sum
- Leetcode习题记录——3Sum Closest
- 个人记录-LeetCode 1.Two Sum
- Leetcode习题记录——Longest Common Prefix
- Leetcode习题:1. Two Sum
- 【LeetCode刷题记录】Two Sum
- Leetcode习题记录—— palindrome和数组求最大的两个数
- Leetcode习题记录——Integer to Roman 和 Roman to Integer
- LeetCode习题笔记——Two Sum
- leetcode -- Two Sum
- Leetcode : Two Sum
- LeetCode 1 - Two Sum
- leetcode two sum
- [leetcode]Two Sum
- LeetCode : Two Sum
- [LeetCode]Two Sum