标签:
一直都想好刷下LeetCode的题目,终于在今年工作的第一天晚上启动了,正好为我的算法学习之路开个头。目前LeetCode里面有179道题,争取两个月内刷完。
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
1 public class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 4 } 5 }
我使用了Java自带的HashMap来实现了hash。
1 import java.util.HashMap; 2 import java.util.Map; 3 public class Solution { 4 public int[] twoSum(int[] numbers, int target) { 5 int len = numbers.length; 6 Map<Integer,Integer> map = new HashMap<Integer,Integer>(); 7 int[] result = new int [2]; 8 for(int i = 0; i < len; i ++){ 9 10 Integer number = new Integer(numbers[i]); 11 Integer index = new Integer(i+1); 12 13 if(!map.containsKey(target - number)){ 14 map.put(number, index); 15 }else if( map.containsKey(target-number)){ 16 result[0]= map.get(target-number); 17 result[1]=i+1; 18 break; 19 } 20 } 21 return result; 22 } 23 }
运行结果:
看了运行的结果,不难发现Java的运行时间明显大于C和C++,于是相同的方法用C++实现了一遍:
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int> &numbers, int target) { 4 int i, sum; 5 vector<int> results; 6 map<int, int> hmap; 7 for(i=0; i<numbers.size(); i++){ 8 int num = numbers[i]; 9 if(!hmap.count(target-num)){ 10 hmap.insert(pair<int, int>(numbers[i], i+1)); 11 }else if(hmap.count(target-num)){ 12 results.push_back(hmap[target-numbers[i]]); 13 results.push_back(i+1); 14 break; 15 } 16 } 17 return results; 18 } 19 };
由此可见,相同的方法,用C++实现比JAVA快了近10倍。
标签:
原文地址:http://www.cnblogs.com/rcfeng/p/4314401.html