2014年1月3日金曜日

Double Duplicates

GroupByとかメソッドチェーンとかRubyの出番かな?!と思ったが、そうは行かなかった。
けっきょくそんな集合演算するよりも、こんなかんじでガリガリ書いたほうがはやいのだ。ということでPython
import sys

def run():
  N=int(sys.stdin.readline(),10)
  arr=sys.stdin.readline().rstrip().split(" ")
  assert len(arr)==N+2

  target = sorted(int(s,10) for s in arr)
  for i in xrange(len(target)-1):
    if target[i]==target[i+1]:
      print target[i]

for i in range(int(sys.stdin.readline())):
  run()

ちなみにメモリくいつつAssertも省略な、馬鹿げた方法でよいなら、Rubyのほうがキレイには書ける。これRuby信者がよく言ってることね。
でもキレイなだけで、メモリ食ってるようじゃダメ。
def run
  STDIN.gets.to_i
  STDIN.gets.split(" ").map{ |s| s.to_i }.sort.group_by{|n| n}.select{|k,v| v.size==2}.each do |k,v|
    puts k
  end
end

STDIN.gets.to_i.times { run }

You've got a list of X+2 numbers containing the numbers 0 through X-1, but with two duplicates. We want to find those duplicates using as little memory as possible. (That's important.)

The first line of the input will be an integer N (1 <= N <= 100).

Each of the following N test cases consists of one line containing an integer X (1 <= X <= 1000), followed by X+2 space-separated integers on the next line.
 
For each test case, print out the two duplicate elements, separated by a newline, with the smaller one first. No blank line between test cases.

Sample Input/Output
1
5
1 2 3 4 0 4 2
2
4

0 件のコメント: