赞
踩
没想到刚工作没多久就遇到了互联网寒冬,公司有大裁员的征兆。又要开始刷题了。
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) } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。