0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Codilityを解く #2 抜けている数字は?

Posted at

問題

公開されてるとはいえ、問題文を直接載せるのはまずそうなので概要のみ。
配列A[n]の要素には、1~(n + 1)の値が一つずつ出てくるが、
一つだけ出てこない数が1~(n + 1)の中にあるので、その数を当てる関数を作る。

example.
solution([2,3,1,5]):   //入力
4              //出力

アプローチ(Python)

1.配列数nを取る。

Aの配列数nはlen(A)で取得できる。

1.py
def solution(A):
    n = len(A)

2.1 ~ n+1の総和aを取る。

繰り返し式でも取れるが、1~nの総和n!は以下で計算したほうが楽。
n! = n(n+1)/2
n → n+1 とすれば、
(n+1)! → (n+1)(n+1+1)/2 = (n+1)(n+2)/2

2.py
def solution(A):
    n = len(A)
    a = (n + 1 )* (n + 2) / 2

3.配列Aの総和bを取る。

forとrangeを使って配列の総和を求める。

3.py
def solution(A):
    n = len(A)
    a = (n + 1 )* (n + 2) / 2
    b = 0
    for i in range(0,n):
        b += A[i]

4.aとbを比較。

1~n+1の合計a > 1~n+1のうち何か欠けているb
a-bで欠けている数字が求まる。

finish.py
def solution(A):
    n = len(A)
    a = (n + 1 )* (n + 2) / 2
    b = 0
    for i in range(0,n):
        b += A[i]
    return(a - b)

これで100点、計算量はO(n) または O(n * log(n))でした。

終わりに

returnとprintを勘違いして半日悶絶していた。
問題文はちゃんと読みましょう。

0
1
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?