首页 > 其他分享 >01.两数之和

01.两数之和

时间:2022-11-20 19:12:03浏览次数:38  
标签:01 target nums int 复杂度 hm 两数 HashMap

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 暴力法
        for(int i=0; i<nums.length;i++) {
            for(int j=i+1;j<nums.length;j++) {
                if (nums[i]+nums[j] == target) {
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }
}
// 时间复杂度O(n2),空间复杂度O(1)

  思路:空间换时间

算法:能快速寻找数组中的是否存在目标元素,如果存在,需要返回它的索引---哈希表(key:元素,value:元素索引)

   class Solution {
    public int[] twoSum(int[] nums, int target) { // 方法描述 空间换时间,只做一次循环 // 定义一个HashMap对象 HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(int i=0; i<nums.length;i++) {
if (hm.containsKey(target-nums[i])) { return new int[] {hm.get(target-nums[i]),i}; } hm.put(nums[i], i); } return null; } }
// 时间复杂度o(n),空间复杂度O(n)

  

标签:01,target,nums,int,复杂度,hm,两数,HashMap
From: https://www.cnblogs.com/liuhe-web-blog/p/16909224.html

相关文章