前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode】两数之和day09

【LeetCode】两数之和day09

作者头像
袁新栋-jeff.yuan
发布2020-08-26 09:45:00
1780
发布2020-08-26 09:45:00
举报

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

解题思路

  1. 暴力破解for循环,进行遍历 然后在其中不加自己

show me Code

代码语言:javascript
复制
{
    public int[] twoSum(int[] nums, int target) {
        int [] result = new int[2];
        for(int i =0 ; i< nums.length;i++){
            for(int j  = 0; j<i+1;j++){
                if(j!=i){
                   if(nums[i] + nums[j] == target){
                    result[0] = j;
                    result[1] = i;
                } 
                }
                
            }
           
        }
         return  result;
    }
}
  1. 两边hash 空间换时间思想
代码语言:javascript
复制
class Solution {
    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++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-06-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
  • show me Code
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档