zoukankan      html  css  js  c++  java
  • LeeCode 1-Two Sum

    Two Sum

    Total Accepted: 125096 Total Submissions: 705262

    Question Solution

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    在一个数组中,找出两个数字的和等于target的下标。

    Java直接暴露找,提交还通过过了,时间复杂度:O(N^2)

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] res = new int[2];
            for(int i=0;i<nums.length-1;i++){
                for(int j=i+1;j<nums.length;j++){
                    if(nums[i]+nums[j] == target){
                        res[0] = i+1;
                        res[1] = j+1;
                    }
                }
            }
            return res;
        }
    }

    下面是根据hashmap,在把数组中的数存在Map之间,先要把target减去数组中的这个数字,对后来进入的数组,判断这个数是否在map中,如果在,说明找到了这两个数

    这样的时间复杂度是O(N)

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            int[] res = new int[2];
            for(int i=0;i<nums.length;i++){
                if(map.containsKey(nums[i])){
                    int index = map.get(nums[i]);
                    res[0] = index + 1;
                    res[1] = i + 1;
                }else{
                    map.put(target - nums[i],i);
                }
            }
            return res;
        }
    }

    下面用Python以此实现上面的两个程序

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            res=[0,0]
            for i in range(len(nums)):
                for j in range(len(nums)):
                    if nums[i] + nums[j] == target:
                        res[0]= i+1
                        res[1]= j+1
                        return res

    很荣幸,这个提示时间超时

    根据字典dict

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dicts = {}
            for i in range(len(nums)):
                if nums[i]  in dicts.keys():
                    return (dicts[nums[i]],i+1)
                else:
                    dicts[target- nums[i]] = i + 1

    字典的key = nums[i],value=i+1

    这里每次是吧target-nums[i] i+1 分布以key 和value 存入字典的,对后面的nums[i] 判断是否在字典中,在的话,说明结束程序

    当然也可以每次吧nums[i] i+1 存在字典中,判断target-nums[i] 是否已经在字典中了

    如下程序,一样AC

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dicts = {}
            for i in range(len(nums)):
                if target - nums[i]  in dicts.keys():
                    return (dicts[target - nums[i]],i+1)
                else:
                    dicts[nums[i]] = i + 1
  • 相关阅读:
    [易学易懂系列|rustlang语言|零基础|快速入门|(18)|use关键词]
    [易学易懂系列|rustlang语言|零基础|快速入门|(17)|装箱crates]
    [易学易懂系列|rustlang语言|零基础|快速入门|(16)|代码组织与模块化]
    区块链行业访谈:《创世访谈录》
    波卡简介
    [易学易懂系列|rustlang语言|零基础|快速入门|(15)|Unit Testing单元测试]
    GIT分布式代码管理系统
    jenkins介绍及部署tomcat环境、部署Maven项目及密码忘记修改
    Docker安装、命令详情、层级架构、docker服务启动失败解决方法
    ELK日志分析系统部署
  • 原文地址:https://www.cnblogs.com/theskulls/p/4755778.html
Copyright © 2011-2022 走看看