|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Seawolf 于 2019-8-16 03:15 编辑
暴力解法:
- class Solution {
- public int[] twoSum(int[] nums, int target) {
-
- int len = nums.length;
-
- int i,j;
-
- int[] array = {-1,-1};
-
- for(i = 0 ; i < len-1; i++){
-
- for(j = i+1; j < len ;j++){
-
- if(nums[i] + nums[j] == target){
-
- array[0] = I;
- array[1] = j;
- return array;
- }
- }
- }
-
- return null;
- }
- }
复制代码
两个for loop,running time O(n^2)
引入hashmap 对算法进行改进:
- class Solution {
-
- public int[] twoSum(int[] nums, int target) {
- Map<Integer, Integer> map = new HashMap<>();
-
- for(int i = 0; i < nums.length; i++) {
- if(map.get(nums[i]) != null) {
- int res[] = {map.get(nums[i]), I};
- return res;
- }
- map.put(target - nums[i], i);
- }
-
- return new int[]{};
- }
- }
复制代码
running time 提高到 O(n) |
|