Programming/์ฝ”ํ…Œ

Codility - Lesson 3 - 2. PermMissingElem

Code Description

An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

 

Your goal is to find that missing element.

 

Write a function:

 

  • def solution(A)

that, given an array A, returns the value of the missing element.

 

For example, given array A such that:

 

     A[0] = 2

     A[1] = 3

     A[2] = 1

     A[3] = 5

 

the function should return 4, as it is the missing element.

 

Write an efficient algorithm for the following assumptions:

 

  • N is an integer within the range [0..100,000];
  • the elements of A are all distinct;
  • each element of array A is an integer within the range [1..(N + 1)].

Code

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(A):
    # write your code in Python 3.6
    
    # X = N, Y = N + 1 ์ •์˜
    X = len(A)
    Y = X + 1
    X_sum = 0
    Y_sum = 0

    # X_sum์— A์˜ list ๊ฐ’์„ ๋ชจ๋‘ ํ•ฉํ•˜์—ฌ ์ €์žฅ
    for a in range(X):
        X_sum = X_sum + A[a]

    # Y_sum์— 1 ~ N + 1 ๊ฐ’์„ ๋ชจ๋‘ ํ•ฉํ•˜์—ฌ ์ €์žฅ
    for a in range(1, Y + 1):
        Y_sum = Y_sum + a

    # Y_sum - X_sum์œผ๋กœ ๋นˆ ๊ฐ’ ๋ฐ˜ํ™˜
    answer = Y_sum - X_sum
  
    return answer

'Programming > ์ฝ”ํ…Œ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

Codility - Lesson 4 - 1. FrogRiverOne  (0) 2021.01.05
Codility - Lesson 3 - 3. TapeEquilibrium  (0) 2021.01.03
Codility - Lesson 3 - 1. FrogJump  (0) 2020.12.18
Codility - Lesson 2 - 1. CyclicRotation  (0) 2020.12.09
Codility - Lesson 1 - 1. BinaryGap  (0) 2020.12.08