首页 > 其他 > 详细

力扣1. 两数之和

时间:2020-05-12 23:09:53      阅读:67      评论:0      收藏:0      [点我收藏+]

法一:暴力法

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3        // 暴力法
 4        for(int i = 0; i < nums.length; i++){
 5            for(int j = i + 1; j < nums.length; j++){
 6                if(nums[i] + nums[j] == target){
 7                    return new int[] {i, j};
 8                }
 9            }
10        }
11        return null;
12     }
13 }

复杂度分析

时间复杂度为O(n^2),空间复杂度为O(1)

 

法二:两次HashMap

 

法三:一次HashMap

思路:

 1. 借助一个HashMap<Integer, Integer>, 存储的元素是一个nums[i] 和 i
 2. 遍历所有的元素,对于每个元素判断互补的那个元素是否在Map中,如果在根据互补的值作为键取出键值对,返回数组,退出循环
 3.  如果不在,则将当前元素和下标作为键值对添加到map中

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         HashMap<Integer, Integer> map = new HashMap<>();
 4         for(int i = 0; i < nums.length; i++){
 5             int another = target - nums[i];
 6             if(map.containsKey(another)){
 7                 int j = map.get(another);
 8                 return new int[] {j, i};
 9             }else{
10                 map.put(nums[i], i);
11             }
12         }
13         return null;
14     }
15 }

 

力扣1. 两数之和

原文:https://www.cnblogs.com/hi3254014978/p/12879440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!