首页 > 其他分享 >Leetcode刷题1.两数之和

Leetcode刷题1.两数之和

时间:2023-09-18 10:47:06浏览次数:52  
标签:target nums int 示例 result 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;
   }

 

 

标签:target,nums,int,示例,result,Leetcode,两数,刷题
From: https://www.cnblogs.com/buguniaogugu/p/17710973.html

相关文章

  • 算法训练day11 栈与队列 02 LeetCode20
    算法训练day11栈与队列02LeetCode20.1047.15020.有效的括号:题目:20.有效的括号-力扣(LeetCode)题解:代码随想录(programmercarl.com)classSolution{public:boolisValid(strings){stack<char>str;if(s.size()%2==1)......
  • 【刷题笔记】52. N-Queens II
    题目Then-queenspuzzleistheproblemofplacingnqueensonann×nchessboardsuchthatnotwoqueensattackeachother.Givenanintegern,returnthenumberofdistinctsolutionstothen-queenspuzzle.Example:Input:4Output:2Explanation:Therea......
  • Leetcode刷题70.爬楼梯
    题目:假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?示例1:输入:n=2输出:2解释:有两种方法可以爬到楼顶。1.1阶+1阶2.2阶示例2:输入:n=3输出:3解释:有三种方法可以爬到楼顶。1.1阶+1阶......
  • leetcode71. 简化路径
     classSolution:defsimplifyPath(self,path:str)->str:li=path.split("/")res=[]foriinli:ifi=='..'andres:res.pop()ifi!='.'andi!='......
  • 算法训练day10 LeetCode 232
    算法训练day10:LeetCode232.225.232.用栈实现队列题目232.用栈实现队列-力扣(LeetCode)题解代码随想录(programmercarl.com)classMyQueue{public:stack<int>stIn;stack<int>stOut;MyQueue(){}voidpush(intx){......
  • 刷题记录(八)
    buuctf-OnePointerPHP题目给了源码:add_api.php:<?phpinclude"user.php";if($user=unserialize($_COOKIE["data"])){ $count[++$user->count]=1; if($count[]=1){ $user->count+=1; setcookie("data",serialize($user)); }el......
  • CTF BugKu平台——Crypto篇刷题记录(后续更新)
    (CTFBugKu平台——Crypto篇)前言记录一下密码学的刷题记录也是为了更好的巩固自己基本有的解码都附有超链接希望大家能顺利通关感谢观看!抄错的字符:描述:老师让小明抄写一段话,结果粗心的小明把部分数字抄成了字母,还因为强迫症把所有字母都换成大写。你能帮小明恢复并......
  • leetcode 加油站——一次遍历
     classSolution:defcanCompleteCircuit(self,gas:List[int],cost:List[int])->int:n=len(gas)max_gas=0rest=0records=[]start=0foriinrange(n):tmp=gas[i]-cost[i]re......
  • 【LeetCode】删除数对后的最小数组长度
    题目给你一个下标从0开始的非递减整数数组nums。你可以执行以下操作任意次:选择两个下标i和j,满足i<j且nums[i]<nums[j]。将nums中下标在i和j处的元素删除。剩余元素按照原来的顺序组成新的数组,下标也重新从0开始编号。请你返回一个整数,表示执行......
  • leetcode 二叉树的最小深度
    给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。说明:叶子节点是指没有子节点的节点。示例1:输入:root=[3,9,20,null,null,15,7]输出:2示例2:输入:root=[2,null,3,null,4,null,5,null,6]输出:5解题思路如果当前节点为null,返......