Leetcode刷题1.两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6 输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6 输出:[0,1]

提示:

  • 2 <= nums.length <= 104

  • -109 <= nums[i] <= 109

  • -109 <= target <= 109

  • 只会存在一个有效答案

 进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?

解答:本题可以采用穷举法用双重for循环来求解

假设target=20

 

 

 

 

 

 

代码如下:

复制代码
public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }
复制代码

时间复杂度为o(n²)

接下来思考如何减少时间复杂度,采用用空间换取时间的方法,我们每次从nums中取一个数把它保存在HashMap中,并与表中的值分别相加,直到找到和为target值的两个数,并将两个数的下标返回出去。

 

 

 

此时7和13相加为20

代码如下:

复制代码
 public int[]twoSum (int[]nums,int target){
       Map<Integer,Integer> storeNums = new HashMap<>(nums.length, 1);
       int[] result = new  int[2];
       for (int i=0;i<nums.length;i++){
           int another = target-nums[i];
           Integer anotherIndex = storeNums.get(another);
           if (null!=anotherIndex){
               result[0]=anotherIndex;
               result[1]=i;
               break;
           }else {
               storeNums.put(nums[i],i);
           }
       }
       return result;
   }
复制代码

 

 

posted @   buguniaogugu  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示