栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣Hot题题解(python,scala,java,c++)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣Hot题题解(python,scala,java,c++)

没想到刚工作没多久就遇到了互联网寒冬,公司有大裁员的征兆。又要开始刷题了。
Leetcode 1 两数之和
https://leetcode-cn.com/problems/two-sum/

# python 1
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        result = []
        for i in range(len(nums)):
            if nums[i] not in dic:
                dic[target-nums[i]] = i
            else:
                result.append(dic[nums[i]])
                result.append(i)
        return result
//scala ver.1.
import scala.collection.mutable
object Solution {
    def twoSum(nums: Array[Int], target: Int): Array[Int] = {
        val map = new mutable.linkedHashMap[Int, Int]
        for(i <- nums.indices){
            if(map.contains(nums(i))){
                return Array(map(nums(i)),i)
            }else{
                map.put(target-nums(i), i)
            }
        }
        Array(0,0)
  }
// scala ver.2.
object Solution {
    def twoSum(nums: Array[Int], target: Int): Array[Int] = {
        var map: Map[Int,Int] = Map()
        for(i <- nums.indices){
            if(map.contains(nums(i))){
                return Array(map(nums(i)),i)
            }else{
                map += (target-nums(i) -> i)
            }
        }
        return Array(0,0)
  }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号