标签:sizeof 算法 cto main tle ber csdn lis 代码
开始就用到了c++的哈希表是真的恶心,首先学习一波基础知识
https://blog.csdn.net/u010025211/article/details/46653519
下面放下大佬的代码
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>a; a.push_back(-1); for(int i=0;i<nums.size();i++) { for(int j=i+1;j<nums.size();j++) if(nums[i]+nums[j]==target) { a[0]=i; a[1]=j; return a; } } } };
这里是完整版代码
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>a; a.push_back(-1); for(int i=0;i<nums.size();i++) { for(int j=i+1;j<nums.size();j++) if(nums[i]+nums[j]==target) { a[0]=i; a[1]=j; return a; } } } }; void trimLeftTrailingSpaces(string &input) { input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { return !isspace(ch); })); } void trimRightTrailingSpaces(string &input) { input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { return !isspace(ch); }).base(), input.end()); } vector<int> stringToIntegerVector(string input) { vector<int> output; trimLeftTrailingSpaces(input); trimRightTrailingSpaces(input); input = input.substr(1, input.length() - 2); stringstream ss; ss.str(input); string item; char delim = ‘,‘; while (getline(ss, item, delim)) { output.push_back(stoi(item)); } return output; } int stringToInteger(string input) { return stoi(input); } string integerVectorToString(vector<int> list, int length = -1) { if (length == -1) { length = list.size(); } if (length == 0) { return "[]"; } string result; for(int index = 0; index < length; index++) { int number = list[index]; result += to_string(number) + ", "; } return "[" + result.substr(0, result.length() - 2) + "]"; } int main() { string line; while (getline(cin, line)) { vector<int> nums = stringToIntegerVector(line); getline(cin, line); int target = stringToInteger(line); vector<int> ret = Solution().twoSum(nums, target); string out = integerVectorToString(ret); cout << out << endl; } return 0; }
这貌似有点高深但是算法复杂度是非常低的,貌似是4msj解决,我们再利用基础的c暴力解决下,
双重循环遍历,代码如下
int* twoSum(int* nums, int numsSize, int target) { int *a; a=(int *)malloc(2*sizeof(int)); for(int i=0;i<numsSize-1;i++) { for(int j=i+1;j<numsSize;j++) { if((nums[i]+nums[j])==target) { a[0]=i; a[1]=j; } } } return a;
但是这个不是最优的,最优算法貌似是采用二分法 代码像这样
int* twoSum(int* nums, int numsSize, int target) { int *a; a=(int *)malloc(2*sizeof(int)); int mid=numsSize/2; for(int i=0;i<mid;i++) { for(int j=mid;j<numsSize;j++) { if((nums[i]+nums[j])==target) { a[0]=i; a[1]=j; } } } return a;
最后在用python解决下吧
def twoSum(self, nums, target): hashmap={} for index, num in enumerate(nums): another_num = target - num if another_num in hashmap: return [hashmap[another_num], index] hashmap[num] = index return None
标签:sizeof 算法 cto main tle ber csdn lis 代码
原文地址:https://www.cnblogs.com/kk328/p/10433487.html