So I was checking the codibility website for online code evaluation. I tried the demo example http://codility.com/c/intro/demoRVC9C9-W8X to familiarize myself with the system.
A zero-indexed 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:
class Solution { public int solution(int[] A); }
that, given a zero-indexed 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] = 5the function should return 4, as it is the missing element. Assume that: 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)].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Here is my solution in Python:
def solution(A):
tmp = [ 0 for x in xrange( len(A) + 1 ) ]
for i,x in enumerate( A ):
tmp[ x - 1 ] = 1
return 1 + tmp.index( 0 )
I was pretty sure that my solution would NOT be accepted because the space complexity is O(n) where n is the size of A. However the system accepted my answer with a perfect score. Am I missing something here?
My solution takes it's base from a ruby perspective.
def solution(a)
(1..(a.count+1)).select{|x| !a.include?(x)}.first
end
def solution(A):
# write your code in Python 2.7
return filter(lambda x: (x not in A), range(1, (len(A)+2)))[0]
This solution resulted 100/100
def solution(A):
if not A:
return 1
sumz=sum(xrange(1,(max(A)+1)))
if ((len(A)+1)) not in A:
return len(A)+1
a_sum=sum(A)
return sumz-a_sum
My solution in Ruby.
def solution(a)
return 1 if a.empty?
ac = a.count
((ac+1)*(ac+2))/2 - a.inject(0, :+)
end
.inject(0, :+) sums up elements in array.
Just start lernig Python and this is my 100 score solution:
def solution(A):
a=[]
a=A
a.sort()
b=0
if len(a)<1:
return 1
if a[0] != 1:
return 1
else:
for x in xrange(0,len(a)):
b=b+int(a[x])
if a[len(a)-1]==len(a)+1:
c=(1+len(a))*len(a)/2
d=b-a[len(a)-1]
e=c-d
return e
else:
return len(a)+1
i know its not great im just start lerning Python
these are two complicated scenarios.
think simply.
step #1: order the array step #2: iterate trough the ordered array. if A[i] != i+1 you have fund the missing element. in case the loop iterates through the whole array than the last element is missing just return the last element + 1.
this is 100% solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.