We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
我看了代码之后才知道是怎么回事,这样表述如何? 利用 HashMap 作为存储,键为目标值减去当前元素值,索引为值,比如 i = 0 时,此时首先要判断 nums[0] = 2 是否在 map的key 中,如果不存在,那么插入键值对 key = 9 - 2 = 7, value = 0,之后当 i = 1 时,此时判断 nums[1] = 7 已存在于 map的key 中,那么取出此时 value = 0 作为第一个返回值,当前 i 作为第二个返回值,具体代码如下所示。
还有虽然思路二只有一个循环,但是为什么我测试了一个发现思路二反而更慢?
public class P01TwoSum {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {2, 7, 11, 15}; int target = 18; //伪代码 long startTime=System.nanoTime(); //获取开始时间 int[] res = twoSum1(nums, target); //测试的代码段 long endTime=System.nanoTime(); //获取结束时间 System.out.println("程序运行时间: "+(endTime-startTime)+"ns"); long startTime1=System.nanoTime(); //获取开始时间 int[] res2 = twoSum2(nums, target); //测试的代码段 long endTime1=System.nanoTime(); //获取结束时间 System.out.println("程序运行时间: "+(endTime1-startTime1)+"ns"); } public static int[] twoSum1(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j =i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] {i,j}; } } } return null; } public static int[] twoSum2(int[] nums, int target) { int len = nums.length; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < len; ++i) { if (map.containsKey(nums[i])) { return new int[]{map.get(nums[i]), i}; } map.put(target - nums[i], i); } return null; }
}
程序运行时间: 2356ns 程序运行时间: 36646ns
The text was updated successfully, but these errors were encountered:
小数据并不能说明什么,可能你初始化 HashMap 就要花很多时间,但在数据量变大的时候和初始化相比时间就相形见绌了
Sorry, something went wrong.
No branches or pull requests
我看了代码之后才知道是怎么回事,这样表述如何?
利用 HashMap 作为存储,键为目标值减去当前元素值,索引为值,比如 i = 0 时,此时首先要判断 nums[0] = 2 是否在 map的key 中,如果不存在,那么插入键值对 key = 9 - 2 = 7, value = 0,之后当 i = 1 时,此时判断 nums[1] = 7 已存在于 map的key 中,那么取出此时 value = 0 作为第一个返回值,当前 i 作为第二个返回值,具体代码如下所示。
还有虽然思路二只有一个循环,但是为什么我测试了一个发现思路二反而更慢?
public class P01TwoSum {
}
程序运行时间: 2356ns
程序运行时间: 36646ns
The text was updated successfully, but these errors were encountered: