今天开始尝试了一下LeetCode,感觉整体格式要求比较规范,能培养规范的代码编写,而且非常注意细节,本来以为第一题非常水不需要编译直接提交也可以,用hash建立映射就可以,没想到看完答案才觉得要精益求精,力求占用最小的时间和空间,看来要学习的东西还很多。贴下题目和代码
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
(1)自己的
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int j = 0; j < nums.length; j++) { map.put(nums[j], j); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution"); }
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); }
Time complexity : O(n). We traverse the list containing n elements only once. Each look up in the table costs only O(1) time.
Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores at most n elements.