首页 > 其他分享 >leetcode-1-easy

leetcode-1-easy

时间:2022-10-31 12:34:33浏览次数:47  
标签:map return target nums int easy Output leetcode

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

思路一:用 map 存储数组值及其下标,遍历判断即可

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }

    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(target - nums[i]) && map.get(target - nums[i]) != i) {
            return new int[]{i, map.get(target - nums[i])};
        }
    }

    return new int[2];
}

标签:map,return,target,nums,int,easy,Output,leetcode
From: https://www.cnblogs.com/iyiluo/p/16843882.html

相关文章

  • C++&Python 描述 LeetCode 1.两数之和
    C++&Python描述LeetCode1.两数之和  大家好,我是亓官劼(qíguānjié),在【亓官劼】公众号、、GitHub、B站、华为开发者论坛等平台分享一些技术博文。放弃不难,但坚持......
  • SpringBoot如何用easyPOI导出excel文件
    在工作中,经常需要我们用Java代码导出一些数据,保存在Excel中。这是非常实用的Excel导出功能,如果我们用SpringBoot结合EasyPOI框架,可以非常方便地实现这个功能。在maven项目中......
  • dp-leetcode152
    动态规划问题,存在重叠子问题/***<p>给你一个整数数组<code>nums</code>&nbsp;,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数......
  • LeetCode刷题记录.Day1
    二分查找基础:二分查找题目链接 LoadingQuestion...-力扣(LeetCode)最开始的题解:classSolution{public:intsearch(vector<int>&nums,inttarget){......
  • LeetCode15. 三数之和
    题意找出数组中三个和为0的数字方法哈希表代码classSolution{public:vector<vector<int>>threeSum(vector<int>&nums){vector<vector<int>>resu......
  • easyexcel 导出 excel 表格数据
    创建一个Springboot项目easyexcel导出excel表格数据创建之后,pom.xml配置<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.o......
  • Leetcode第784题:字母大小写的全排列(Letters case permutation)
    解题思路使用回溯法。从左往右依次遍历字符,当遍历到字符串s的第i个字符c时:如果c为一个数字,继续检测下一个字符。如果c为一个字母,将其进行大小写转换,然后往后继续遍历;完......
  • Leetcode: 俩球之间的磁力
    题目在代号为C-137的地球上,Rick发现如果他将两个球放在他新发明的篮子里,它们之间会形成特殊形式的磁力。Rick有 n 个空的篮子,第 i 个篮子的位置在 position[i] ,Mo......
  • Leetcode 6233 -- dfs序
    题目描述给定我们一棵树,和一组查询,每个查询给出一个节点,让我们求删除以这个节点为根(包括这个节点)的子树中的所有节点之后(并不是真的删除),剩下的树中节点的最大高度。(树的......
  • leetcode-989-easy
    AddtoArray-FormofIntegerThearray-formofanintegernumisanarrayrepresentingitsdigitsinlefttorightorder.Forexample,fornum=1321,thearr......