Sunday, September 3, 2017

Codility - Lesson 4 Counting elements - 1. MissingInteger

Source Link:
https://codility.com/programmers/lessons/4-counting_elements/missing_integer/

Question:
This is a demo task.
Write a function:

class Solution { public int solution(int[] A); }
 
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
For another example, given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Assume that:
  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [−1,000,000..1,000,000].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

My Solution:
Notes:
1.  special case
if(A.length ==0){
return 1;
}
2.  Using "set" to check if an element has appeared
// note: need to "import java.util.*" (important)
Set<Integer> set = new HashSet<Integer>(); 
3. add elements into the set
for(int i=0; i< A.length; i++){
set.add(A[i]);
}
4.  note: the missing number is not possible bigger than (A.length) because there are only (A.length) numbers
for(int i=1; i<= A.length; i++){
if(set.contains(i) != true) // the 1st missing element
return i;
}
5. If there are no missing numbers from 1 to A.length, the missing number is "A.length+1" (important)
return A.length+1;

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...