1. Two Sum(两个数求和)(leetcode)
分析:
1、第一次写是用双for循环写的,复杂度太高,pass
2、看答案,引用哈希表定位两者之间的对应关系,快了一倍。
运行时间:3ms 时间复杂度:o(n)
class Solution { public int[] twoSum(int[] nums, int target) { int[] result=new int[2]; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(target-nums[i])){ result[0]=map.get(target-nums[i])+1; result[1]=i+1; return result; } map.put(nums[i],i); } return result; } }
之前没看懂result赋值部分,要注意是将map中的值赋给result而不是nums中的。
3、考虑用双指针。这里涉及到给出的数组是否已经排好序,如果已经排好了,用双指针并行的时间复杂度是o(n/2);
题目167. Two Sum II - Input array is sorted(数组已排序的两个数求和)
Given an array of integers that is already sorted in ascending order, 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.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
方法一:双指针法
双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。
时间复杂度:o(n/2) 运行时间:0ms 占用内存:35.8 MB
class Solution { public int[] twoSum(int[] numbers, int target) { int i=0; int j=numbers.length-1; while (i<j){ int sum=numbers[i]+numbers[j]; if(target==sum){ return new int[]{i+1,j+1}; }else if(target>sum){ i++; }else { j--; } } return null; } }
方法二:hashmap和上题同一个解法;
时间复杂度:o(n) 运行时间:2ms 占用空间:36mb
class Solution { public int[] twoSum(int[] numbers, int target) { int [] result=new int[2]; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<numbers.length-1;i++){ if(map.containsKey(target-numbers[i])){ result[0]=map.get(target-numbers[i])+1; result[1]=i+1; } map.put(numbers[i],i); } return result; } }
苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。