Question: I CODE THIS WRONG, THE EXPECTED OUT IS 0,-1, but I keep getting -1,-1. Please fix this code for the expected output is 0, -1

I CODE THIS WRONG, THE EXPECTED OUT IS 0,-1, but I keep getting -1,-1. Please fix this code for the expected output is 0, -1

 

 

 

import java.util.Stack;


 

public class hwkp4 {


 

// method that finds the leader element

// which appears more than half of the list elements

// returns the leader

// if leader not found then returns -1


 

static int leader(int[] a) {

// base cas


 

Stack stack = new Stack<>();

 

// do for each element

for(int i = 0; i < a.length;){


 

{

// pop all the elements that are less than the current element

while (!stack.isEmpty() && stack.peek() < i) {

stack.pop();

}

// push current element into the stack

stack.push(i);

}

int num = a[stack.peek()];

int count = 0;


 

for(i = 0; i < a.length; i++){

if(a[i] == num){

}

}


 

if(count < a.length / 2){

return -1;

}


 

return stack.pop();}

return 0;

}

public static void main(String argv[]) {


 

int[] a = {23, 23, 67, 23, 67, 23, 45};

System.out.println(leader(a));

 

int[] a1 = {23, 24, 67, 23, 67, 23, 45};

System.out.println(leader(a1));

 

}


 

}


Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

It seems like the code is trying to identify a leader in the array where a leader is defined as any number occurring more than half the times in the a... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!