Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
String string = Arrays.toString(nums);
string = string.substring(1, string.length()-1);
string = string.replace(", ", "");
int i = 0;
char max = string.charAt(i);
int temp = 0;
System.out.println(string);
while (i < string.length()) {
int index = string.lastIndexOf(string.charAt(i));
if(temp < index-i){
temp = index - i;
max = string.charAt(i);
}
i = index+1;
}
return Character.getNumericValue(max);
}
}