iT邦幫忙

1

Ruby幼幼班--Single Number

  • 分享至 

  • xImage
  •  

Yes


Single Number

黑魔法集合....

題目連結:https://leetcode.com/problems/single-number/
題目提示:陣列中,一個元素最多2個,其中一個只有一次。

整理

# @param {Integer[]} nums
# @return {Integer}
def single_number(nums)

end

p single_number([2,2,1])  #=> 1
p single_number([4,1,2,1,2])  #=> 4
p single_number([1])  #=> 1

跑迴圈or迭代

略....

查表

其實Ruby查表法很方便,枚舉習慣後。

def single_number(nums)
  #變成hash, key == 數值, value == 個數
  #挑出個數1的key(value是1的)
end
def single_number(nums)
  #變成hash, key == 數值, value == 個數
  new_hash = nums.tally
  
  #挑出個數1的key(value是1的)
  new_hash.key(1)
end


#tally:Tallies the collection, i.e., counts the occurrences of each element. Returns a hash with the elements of the collection as keys and the corresponding counts as values.

2.7.3 :001 > ["a", "a", "b", "c", "c", "c"].tally
 => {"a"=>2, "b"=>1, "c"=>3} 
2.7.3 :003 > [4,1,2,1,2].tally
 => {4=>1, 1=>2, 2=>2} 
 
#補充Hash.index()
2.7.3 :002 > {"a"=>2, "b"=>1, "c"=>3}.index(1)
 => "b" 
2.7.3 :006 > {"a"=>2, "b"=>1, "c"=>3}.index(2)
 => "a" 
2.7.3 :007 > {"a"=>2, "b"=>1, "c"=>3}.index(3)
 => "c"
 
#補充invert
2.7.3 :020 > {"a"=>2, "b"=>1, "c"=>3}.invert
 => {2=>"a", 1=>"b", 3=>"c"} 
2.7.3 :023 > {"a"=>2, "b"=>1, "c"=>3}.invert[1]
 => "b" 
2.7.3 :024 > {"a"=>2, "b"=>1, "c"=>3}.invert[2]
 => "a" 
2.7.3 :025 > {"a"=>2, "b"=>1, "c"=>3}.invert[3]
 => "c" 

整理

def single_number(nums)
  nums.tally.key(1)
end

數學

2.7.3 :027 > 1 + 1
 => 2 
2.7.3 :028 > 2 - 1
 => 1 
def single_number(nums)
  nums.uniq.sum * 2 - nums.sum
end

2 + 1 + 2 + 1 
-
2 + 2 + 1
=
1

查表法比較慢,但是萬用。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言