leetcode链接:
https://leetcode.cn/problems/two-sum/
方案一:暴力枚举
自行做出
1 2 3 4 5 6 7
| for (int i = 0; i < nums.length -1; i++) { for (int j = i+1; j < nums.length; j++) { if (nums[i] + nums[j] == target) return new int[]{i,j}; } } return nums;
|
结果
解答成功:
执行耗时:58 ms,击败了14.31% 的Java用户
内存消耗:42.4 MB,击败了32.18% 的Java用户
方案二:哈希表
https://leetcode.cn/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; ++i) { if (hashtable.containsKey(target - nums[i])) { return new int[]{hashtable.get(target - nums[i]), i}; } hashtable.put(nums[i], i); } return new int[0]; } }
作者:LeetCode-Solution 链接:https: 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|