Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!
In my code k is the highest value in the input array.
Code:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.
So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].
To fix this change your first loop to:
for (int i = 0; i < k; i++){
In the last loop you will get the same exception cause input[8] doesn't exist.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] input = {0,1,1,3,4,5,3,0};
int[] output = new int[input.length];
int k = 5; // k is the largest number in the input array
System.out.println("before sorting:");
System.out.println(Arrays.toString(input));
output = countingSort(input, output, k);
System.out.println("after sorting:");
System.out.println(Arrays.toString(output));
}
public static int[] countingSort(int[] input, int[] output, int k) {
int counter[] = new int[k + 1];
for (int i : input) { counter[i]++; }
int ndx = 0;
for (int i = 0; i < counter.length; i++) {
while (0 < counter[i]) {
output[ndx++] = i;
counter[i]--;
}
}
return output;
}
}
Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html
this may help but try using the Arraya.sort() method.
e.g:
//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
As per algorithm following implementation, I have prepared for the count sort technique
public static int[] countSort(int elements[]) {
int[] sorted = new int[elements.length+1];
int[] range = new int[getMax(elements)+1];
for(int i=0;i<range.length;i++) {
range[i] = getCount(i, elements);
try {
range[i] = range[i]+range[i-1];
}catch(ArrayIndexOutOfBoundsException ae) {
continue;
}
}
for(int i=0;i<elements.length;i++) {
sorted[range[elements[i]]] = elements[i];
range[elements[i]] = range[elements[i]]-1;
}
return sorted;
}
public static int getCount(int value,int[] elements) {
int count = 0;
for(int element:elements) {
if(element==value) count++;
}
return count;
}
public static int getMax(int elements[]) {
int max = elements[0];
for(int i=0;i<elements.length;i++) {
if(max<elements[i]) {
max = elements[i];
}
}
return max;
}
Please review and let me know if any feedback and it is more helpful.
Note :
Non-negative no won't support in the above implementation.
don't use 0th index of the sorted array.
Related
Okay, so i need to find all the negative numbers of array and return them.I found the negative number, but how do i return them all? P.S yes i am a beginner.
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
System.out.println(findNumber(array));
}
public static int findNumber(int[] sum) {
int num = 0;
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < num) {
num = sum[i];
}
}
return num;
}
Java 8 based solution. You can use stream to filter out numbers greater than or equal to zero
public static int[] findNumber(int[] sum)
{
return Arrays.stream(sum).filter(i -> i < 0).toArray();
}
There are multiple ways of doing this, if you just want to output all of the negative numbers easily you could do this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
ArrayList<Integer> negativeNumbers = findNumber(sum);
for(Integer negNum : negativeNumbers) {
System.out.println(negNum);
}
}
public static ArrayList<Integer> findNumber(int[] sum) {
ArrayList<Integer> negativeNumbers = new ArrayList<>();
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < 0) {
negativeNumber.add(sum[i]);
}
}
return negativeNumbers;
}
As you told you are beginner, i'm giving code in using arrays only.
Whenever you come across a negative number, just add it to the array and increment it's index number and after checking all the numbers, return the array and print it.
public static void main(String[] args)
{
int [] array = {5,-1,6,3,-20,10,20,-5,2};
int[] neg = findNumber(array);
for(int i = 0 ; i<neg.length; i++)
{
System.out.println(neg[i]);
}
}
public static int[] findNumber(int[] a)
{
int j=0;
int[] n = new int[a.length];
for(int i = 0; i<a.length ; i++)
{
if(a[i] <0)
{
n[j] = a[i];
j++;
}
}
int[] neg = new int[j];
for( int k = 0 ; k < j ; k++)
{
neg[k] = n[k];
}
return neg;
}
I hope it helps.
You can modify your method to iterate through the array of numbers, and add every negative number you encounter, to a List.
public static List<Integers> findNegativeNumbers(int[] num) {
List<Integers> negativeNumbers = new ArrayList<>();
for (int i = 0; i < num.length; i++) {
if(num[i] < 0) {
negativeNumbers.add(num[i]);
}
}
return negativeNumbers;
}
You could then print out the list of negative numbers from this method itself, or return the list with return to be printed in main.
You code is returning the sum of elements, but I understood that you wanted every negative number.
So, I assumed you want something like this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
Integer [] result = findNumbers( array );
for( int i : result )
{
System.out.println( i );
}
}
public static Integer[] findNumbers(int[] v) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < v.length ; i++) {
if(v[i] < 0) {
list.add(v[i]);
}
}
return list.toArray( new Integer[0] );
}
Is it?
Best regards.
public static int[] findNum(int[] array)
{
int negativeIntCount = 0;
int[] negativeNumbers = new int[array.length];
for(int i = 0; i < array.length; i++)
{
if(array[i] < 0)
{
negativeIntCount++;
negativeNumbers[i] = array[i];
}
}
System.out.println("Total negative numbers in given arrays is " + negativeIntCount);
return negativeNumbers;
}
To display as an array in output :
System.out.println(Arrays.toString(findNum(array)));
To display output as space gaped integers :
for(int x : findNum(array))
{
System.out.print(" " + x)
}
I'm trying to count the number of occurences of ints, one to six inclusive, in an array of size 6. I want to return an array with the number of times an int appears in each index, but with one at index zero.
Example:
Input: [3,2,1,4,5,1,3]
Expected output: [2,1,2,1,1,0].
Problem:
It outputs [1,1,3,0,1,0] with the code excerpt below. How can I fix this? I can't find where I'm going wrong.
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
}
return amt;
}
public int[] countNumOfEachScore(){
int[] scores = new int[6];
int[] counts = new int[6];
for (int i = 0; i < 6; i++){
scores[i] = dice[i].getValue();
}
for (int j = 0; j < 6; j++){
counts[j] = arrayCount(scores, j+1);
}
return counts;
}
dice[] is just an array of Die objects, which have a method getValue() which returns an int between 1 and 6, inclusive. counts[] is the int array with the wrong contents.
It'll be faster to write another code instead of debugging yours.
public static int[] count(int[] array) {
int[] result = new int[6];
for (int i = 0; i < array.length; i++) {
try{
result[array[i]-1]++;
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException("The numbers must be between 1 and 6. Was " + String.valueOf(array[i]));
}
}
return result;
}
The above will result in an array of 6 ints. ith number in the result array will store the number of occurences of i+1.
PoC for the OP
public static void main(String [] args){
int []ar=new int[]{3,2,1,4,5,1,3};
System.out.println(Arrays.toString(counter(ar)));
}
public static int[] counter(int []ar){
int []result=new int [6];
for(int i=0;i<ar.length;i++){
int c=0;
for(int j=0;j<ar.length;j++){
if(j<i && ar[i]==ar[j])
break;
if(ar[i]==ar[j])
c++;
if(j==ar.length-1){
result[i]=c;
}
}
}
return result;
}
I have created my version of the merge sort algorithm in java code. My issues are these: when I run the code as is, I get a NullPointerExecpetion in the main on line 27 (see commented line). And I know there is way to make the method calls and instantiate newArray without them being static but Im not quite sure how.. can someone help fix these? I am still relatively new to java so be nice :)
Main:
import java.util.Random;
public class MergeSort_main
{
public static void main(String[] args)
{
int[] originalArray = new int[1000];
Random rand = new Random();
for (int i = 0; i < originalArray.length; i++)
{
int randNum = rand.nextInt(1000)+1;
originalArray[i] = randNum;
}
for(int i = 0; i < originalArray.length; i++)
{
System.out.println(i+"." + originalArray[i]);
}
System.out.println("---------------------End Random Array-------\n");
MergeSortAlgorithm.mergeSortAlg(originalArray);
int[] sortedArray = MergeSortAlgorithm.getSortedArray();
for(int i = 0; i < sortedArray.length; i++) //NULL POINTER EXCEPTION HERE
{
System.out.println(i+ "." + sortedArray[i]);
}
}
}
Algorithm Class:
public class MergeSortAlgorithm
{
private static int[] newArray;
public static void mergeSortAlg(int[] randomNums)
{
int size = randomNums.length;
if (size < 2)
{
return; //if the array can not be split up further, stop attempting to split.
}
int half = size / 2;
int firstHalfNums = half;
int secondHalfNums = size - half;
int[] firstArray = new int[firstHalfNums];
int[] secondArray = new int[secondHalfNums];
for (int i = 0; i < half; i++)
{
firstArray[i] = randomNums[i];
}
for (int i = half; i < size; i++)
{
secondArray[i - half] = randomNums[i];
}
mergeSortAlg(firstArray);
mergeSortAlg(secondArray);
merge(firstArray, secondArray, randomNums);
}
public static void merge(int[] firstArray, int[] secondArray, int[] newArray)
{
int firstHalfNums = firstArray.length;
int secondHalfNums = secondArray.length;
int i = 0; //iterator for firstArray
int j = 0; //iterator for second array
int k = 0; //interator for randomNums array
while (i < firstHalfNums && j < secondHalfNums)
{
if (firstArray[i] <= secondArray[j])
{
newArray[k] = firstArray[i];
i++;
k++;
}
else
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
while (i < firstHalfNums)
{
newArray[k] = firstArray[i];
k++;
i++;
}
while (j < firstHalfNums)
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
public static int[] getSortedArray()
{
return newArray;
}
}
Basically, the only problem with your code is that you don't initialize newArray with any values, resulting in a null.
You are also redefining newArray at the top of your merge function .
The problem is that newArray[] is never instantiated i.e. newArray reference is pointing to null. And, no change is made in the newArray so value or reference returned to main is null. And, then you are performing sortedArray.length where sorted array having a null value.
You have to make newArray[] point to randomNums[].
public class intersect {
public static void find(int[] a, int[] b, int[] acc)
{
int position = 0;
for (int j = 0; j < a.length; j++) {
for (int k = 0; k<b.length; k++) {
if (a[j] == b[k]) {
acc[position] = b[k];
position++;
}
}
}
System.out.println(java.util.Arrays.toString(acc));
}
public static void main (String[] s)
{
int[] acc = new int[2];
int[] a = {1,2,3};
int[] b = {2,3,4};
find(a, b, acc);
}
}
I have written the above code to solve the problem.
But if you see, the function is very limited because I have to change the length of the acc every time. That means I have to know how many elements are intersecting. In this case, the array {1,2,3} and {2,3,4} have {2,3} in common, so the length of the acc would be 2.
I am sure there are millions of ways of tackling this problem, but I cannot seem to think of a way of fixing this.
Please help!
If your professor wants you to use arrays, you can use the following method:
public static int[] resize(int[] arr)
{
int len = arr.length;
int[] copy = new int[len+1];
for (int i = 0; i < len; i++)
{
copy[i] = arr[i];
}
return copy;
}
This will increase the size of the array by 1. You can use that instead. By the way, you're not using the fact that they're sorted in your find() method. What you should do is this:
public static void find(int[] a, int[] b, int[] acc)
{
int a_index = 0, b_index = 0, acc_index = -1;
int a_element, b_element;
while (a_index < a.length && b_index < b.length)
{
a_element = a[a_index]; b_element = b[b_index];
if (a_element == b_element)
{
acc = resize(acc);
acc[++acc_index] = a_element;
a_index++; b_index++;
} else if (b_element < a_element) {
b_index++;
} else {
a_index++;
}
}
System.out.println(java.util.Arrays.toString(acc));
}
This method is more efficient now. Working example.
To find intersection of 2 sorted arrays, follow the below approach :
1) Use two index variables i and j, initial values with 0
2) If array1 is smaller than array2 then increment i.
3) If array1 is greater than array2 then increment j.
4) If both are same then print any of them and increment both i and j.
check this link for more information
https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/
public class FindIntersection {
static void findInterSection(int array1[], int array2[], int array1NoOfElements, int
array2NoOfElements) {
int i = 0, j = 0;
while (i < array1NoOfElements && j < array2NoOfElements) {
if (array1[i] < array2[j]) {
i++;
} else if (array2[j] < array1[i]) {
j++;
}
// if both array elements are same
else {
System.out.println(array2[j++] + " ");
i++;
}
}
}
public static void main(String[] args)
{
int myFirstArray[] = { 1, 2, 4, 5, 5 };
int mySecondArray[] = { 2, 3, 5, 7 };
int m = myFirstArray.length;
int n = mySecondArray.length;
findInterSection(myFirstArray, mySecondArray, m, n);
}
}
Make your intersection array's size the size of the smaller of your original arrays. That way, you won't ever have to increase it's capacity.
Then you can use Arrays.copy to transfer your results into an appropriately sized array.
Not sure if this is the best solution, but you don't need to hard-code the size of the intersection ahead of time (which is one thing you were concerned about).
As you iterate through both arrays, you can add elements found in both sets to a StringBuilder (along with some delimiter, I used a comma in the example below). Once you're finished, you can call toString() & then split() using the delimiter afterwards to get a String[]. At that point, you can put convert those String objects to int primitives & return an int[].
public class Scratch {
public static void main(String[] s) {
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
int[] intersection = findIntersection(a, b);
System.out.println(Arrays.toString(intersection));
}
public static int[] findIntersection(int[] a, int[] b) {
StringBuilder intersectionStringBuilder = new StringBuilder();
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < b.length; k++) {
if (a[j] == b[k])
intersectionStringBuilder.append(a[j] + ",");
}
}
String[] intersectionStringArray = intersectionStringBuilder.toString().split(",");
int[] intersection = new int[intersectionStringArray.length];
for (int current = 0; current < intersectionStringArray.length; current++) {
intersection[current] = Integer.parseInt(intersectionStringArray[current]);
}
return intersection;
}
}
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j] && !index.contains(j)){
list.add(arr1[i]);
index.add(j);
break;
}
}
}
int result[]=new int[list.size()];
int k=0;
for(int i:list){
result[k]=i;
k++;
}
for(int i=0;i<result.length;i++){
System.out.println(result[i]);
}
return result;
}
Find the first covering prefix of a given array.
A non-empty zero-indexed array A consisting of N integers is given. The first covering
prefix of array A is the smallest integer P such that and such that every value that
occurs in array A also occurs in sequence.
For example, the first covering prefix of array A with
A[0]=2, A[1]=2, A[2]=1, A[3]=0, A[4]=1 is 3, because sequence A[0],
A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in
array A.
My solution is
int ps ( int[] A )
{
int largestvalue=0;
int index=0;
for(each element in Array){
if(A[i]>largestvalue)
{
largestvalue=A[i];
index=i;
}
}
for(each element in Array)
{
if(A[i]==index)
index=i;
}
return index;
}
But this only works for this input, this is not a generalized solution.
Got 100% with the below.
public int ps (int[] a)
{
var length = a.Length;
var temp = new HashSet<int>();
var result = 0;
for (int i=0; i<length; i++)
{
if (!temp.Contains(a[i]))
{
temp.Add(a[i]);
result = i;
}
}
return result;
}
I would do this
int coveringPrefixIndex(final int[] arr) {
Map<Integer,Integer> indexes = new HashMap<Integer,Integer>();
// start from the back
for(int i = arr.length - 1; i >= 0; i--) {
indexes.put(arr[i],i);
}
// now find the highest value in the map
int highestIndex = 0;
for(Integer i : indexes.values()) {
if(highestIndex < i.intValue()) highestIndex = i.intValue();
}
return highestIndex;
}
Your question is from Alpha 2010 Start Challenge of Codility platform. And here is my solution which got score of 100. The idea is simple, I track an array of counters for the input array. Traversing the input array backwards, decrement the respective counter, if that counter becomes zero it means we have found the first covering prefix.
public static int solution(int[] A) {
int size = A.length;
int[] counters = new int[size];
for (int a : A)
counters[a]++;
for (int i = size - 1; i >= 0; i--) {
if (--counters[A[i]] == 0)
return i;
}
return 0;
}
here's my solution in C#:
public static int CoveringPrefix(int[] Array1)
{
// Step 1. Get length of Array1
int Array1Length = 0;
foreach (int i in Array1) Array1Length++;
// Step 2. Create a second array with the highest value of the first array as its length
int highestNum = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array1[i] > highestNum) highestNum = Array1[i];
}
highestNum++; // Make array compatible for our operation
int[] Array2 = new int[highestNum];
for (int i = 0; i < highestNum; i++) Array2[i] = 0; // Fill values with zeros
// Step 3. Final operation will determine unique values in Array1 and return the index of the highest unique value
int highestIndex = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array2[Array1[i]] < 1)
{
Array2[Array1[i]]++;
highestIndex = i;
}
}
return highestIndex;
}
100p
public static int ps(int[] a) {
Set<Integer> temp = new HashSet<Integer>();
int p = 0;
for (int i = 0; i < a.length; i++) {
if (temp.add(a[i])) {
p = i+1;
}
}
return p;
}
You can try this solution as well
import java.util.HashSet;
import java.util.Set;
class Solution {
public int ps ( int[] A ) {
Set set = new HashSet();
int index =-1;
for(int i=0;i<A.length;i++){
if(set.contains(A[i])){
if(index==-1)
index = i;
}else{
index = i;
set.add(A[i]);
}
}
return index;
}
}
Without using any Collection:
search the index of the first occurrence of each element,
the prefix is the maximum of that index. Do it backwards to finish early:
private static int prefix(int[] array) {
int max = -1;
int i = array.length - 1;
while (i > max) {
for (int j = 0; j <= i; j++) { // include i
if (array[i] == array[j]) {
if (j > max) {
max = j;
}
break;
}
}
i--;
}
return max;
}
// TEST
private static void test(int... array) {
int prefix = prefix(array);
int[] segment = Arrays.copyOf(array, prefix+1);
System.out.printf("%s = %d = %s%n", Arrays.toString(array), prefix, Arrays.toString(segment));
}
public static void main(String[] args) {
test(2, 2, 1, 0, 1);
test(2, 2, 1, 0, 4);
test(2, 0, 1, 0, 1, 2);
test(1, 1, 1);
test(1, 2, 3);
test(4);
test(); // empty array
}
This is what I tried first. I got 24%
public int ps ( int[] A ) {
int n = A.length, i = 0, r = 0,j = 0;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
if ((long) A[i] == (long) A[j]) {
r += 1;
}
if (r == n) return i;
}
}
return -1;
}
//method must be public for codility to access
public int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);
int index= A[0];
for (int i = 0; i < A.length; i++) {
if( set.contains(A[i])) continue;
index = i;
set.add(A[i]);
}
return index;
}
this got 100%, however detected time was O(N * log N) due to the HashSet.
your solutions without hashsets i don't really follow...
shortest code possible in java:
public static int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);//avoid resizing
int index= -1; //value does not matter;
for (int i = 0; i < A.length; i++)
if( !set.contains(A[i])) set.add(A[index = i]); //assignment + eval
return index;
}
I got 100% with this one:
public int solution (int A[]){
int index = -1;
boolean found[] = new boolean[A.length];
for (int i = 0; i < A.length; i++)
if (!found [A[i]] ){
index = i;
found [A[i]] = true;
}
return index;
}
I used a boolean array which keeps track of the read elements.
This is what I did in Java to achieve 100% correctness and 81% performance, using a list to store and compare the values with.
It wasn't quick enough to pass random_n_log_100000 random_n_10000 or random_n_100000 tests, but it is a correct answer.
public int solution(int[] A) {
int N = A.length;
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i=0; i<N; i++){
if(!temp.contains(A[i])){
temp.add(A[i]);
}
}
for(int j=0; j<N; j++){
if(temp.contains(A[j])){
temp.remove((Object)A[j]);
}
if(temp.isEmpty()){
return j;
}
}
return -1;
}
Correctness and Performance: 100%:
import java.util.HashMap;
class Solution {
public int solution(int[] inputArray)
{
int covering;
int[] A = inputArray;
int N = A.length;
HashMap<Integer, Integer> map = new HashMap<>();
covering = 0;
for (int i = 0; i < N; i++)
{
if (map.get(A[i]) == null)
{
map.put(A[i], A[i]);
covering = i;
}
}
return covering;
}
}
Here is my Objective-C Solution to PrefixSet from Codility. 100% correctness and performance.
What can be changed to make it even more efficient? (without out using c code).
HOW IT WORKS:
Everytime I come across a number in the array I check to see if I have added it to the dictionary yet.
If it is in the dictionary then I know it is not a new number so not important in relation to the problem. If it is a new number that we haven't come across already, then I need to update the indexOftheLastPrefix to this array position and add it to the dictionary as a key.
It only used one for loop so takes just one pass. Objective-c code is quiet heavy so would like to hear of any tweaks to make this go faster. It did get 100% for performance though.
int solution(NSMutableArray *A)
{
NSUInteger arraySize = [A count];
NSUInteger indexOflastPrefix=0;
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<arraySize; i++)
{
if ([myDict objectForKey:[[A objectAtIndex:i]stringValue]])
{
}
else
{
[myDict setValue:#"YES" forKey:[[A objectAtIndex:i]stringValue]];
indexOflastPrefix = i;
}
}
return indexOflastPrefix;
}
int solution(vector &A) {
// write your code in C++11 (g++ 4.8.2)
int max = 0, min = -1;
int maxindex =0,minindex = 0;
min = max =A[0];
for(unsigned int i=1;i<A.size();i++)
{
if(max < A[i] )
{
max = A[i];
maxindex =i;
}
if(min > A[i])
{
min =A[i];
minindex = i;
}
}
if(maxindex > minindex)
return maxindex;
else
return minindex;
}
fwiw: Also gets 100% on codility and it's easy to understand with only one HashMap
public static int solution(int[] A) {
// write your code in Java SE 8
int firstCoveringPrefix = 0;
//HashMap stores unique keys
HashMap hm = new HashMap();
for(int i = 0; i < A.length; i++){
if(!hm.containsKey(A[i])){
hm.put( A[i] , i );
firstCoveringPrefix = i;
}
}
return firstCoveringPrefix;
}
I was looking for the this answer in JavaScript but didn't find it so I convert the Java answer to javascript and got 93%
function solution(A) {
result=0;
temp = [];
for(i=0;i<A.length;i++){
if (!temp.includes(A[i])){
temp.push(A[i]);
result=i;
}
}
return result;
}
// you can also use imports, for example:
import java.util.*;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> s = new HashSet<Integer>();
int index = 0;
for (int i = 0; i < A.length; i++) {
if (!s.contains(A[i])) {
s.add(A[i]);
index = i;
}
}
return index;
}
}