-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion169.java
More file actions
70 lines (63 loc) · 1.14 KB
/
Copy pathQuestion169.java
File metadata and controls
70 lines (63 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Author: Ananthanarayanan R
Section: Algorithms
Question: 169
*/
public class Question169
{
public static boolean check(int[] arr,int num)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i] == num)
return true;
}
return false;
}
public static int findIndex(int[] arr,int num)
{
for(int i = 0;i<arr.length;i++)
{
if(arr[i] == num)
return i;
}
return 0;
}
public static int majorityElement(int[] nums)
{
int[] temp = new int[nums.length];
int[] count = new int[nums.length];
int index=0;
int i,j;
for(i=0;i<nums.length;i++)
{
if(!check(temp,nums[i]))
{
temp[index] = nums[i];
count[index] = 1;
index++;
}
else
{
count[findIndex(temp,nums[i])]++;
}
}
int max = Integer.MIN_VALUE;
int maxIndex = 0;
for(i=0;i<index;i++)
{
if(count[i]>max)
{
max = count[i];
maxIndex = i;
}
}
return temp[maxIndex];
}
public static void main(String[] args)
{
System.out.println("Main Method starts");
int[] nums = {1,1,1,1,1,2,2,2};
System.out.println(majorityElement(nums));
}
}