LeetCode || 001 Two Sum

来源:互联网 发布:java rmi反序列化 exp 编辑:程序博客网 时间:2024/05/15 23:54

题目:Two Sum (Easy)


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].


分析解答

给定了唯一解限定、vector配合class的测试,输入省去了数据输入输出的麻烦。确实是比较简单的一道题目,问题仅仅在于效率如何提高上面。
下面列举几种可能的算法分析和测试结果。
算法1:暴力搜索
class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int N = nums.size();for (int i = 0; i < N-1; i++)for (int j = i+1; j < N; j++){if (nums[i] + nums[j] == target){vector <int> result;result.push_back(i);result.push_back(j);return(result);}}    }};
算法的想法及其简单,就是一轮冒泡对比,如果相加得到可行的解,则立刻返回结果结束程序。
Result:2017年2月,LeetCode平台,AC,190ms,优于30%的算法。

算法2:哈希法(简单查表)

0 0
原创粉丝点击