Checking one dimensional array for duplicate integers Java - java

hey guys,
right i have an array of 50 random integers and i have to check if any of them are the same,
here is my code so far it only checks ajacent indexs
for (int i =0; i < 50; i++)
{
System.out.print("Student" + i + ": " );
customers[i] = (int)((Math.random()*10000)%10+1);
System.out.print(" " +customers[i]+ "\n");
if( duplicate == customers[i])
{
System.out.println("yup");
}
duplicate = customers[i];
}

Sort the array first. Then you can check just the next index. If it's ever the same, break.
Okay, I hate ridiculous limitations. If you want, you can do it like this without using a sort:
import java.util.ArrayList;
import java.lang.Math;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Integer currentValue = 0;
int i = 0;
int limit = 20;
for(i = 0; i < limit; i++) {
list.add((int)(Math.random() * 100));
}
for(i = 0; i < limit; i++) {
currentValue = list.get(i);
list.set(i, -1);
if(list.contains(currentValue)) {
System.out.println("yup:" + currentValue);
return;
} else {
list.set(i, currentValue);
}
}
System.out.println("No duplicates!");
return;
}
}
Is it efficient? No.
Does it work? Yes.

I think, if you have to just use if/for functions, you have to make two loops:
for (int i =0; i < 50; i++)
{
customers[i] = (int)((Math.random()*10000)%10+1);
for ( int j = 0; j < i; j++)
{
if( customers[j] == customers[i])
{
// duplicated entry. do what you want
System.out.println("yup");
}
}
}

You could use Arrays.sort (see more at http://www.exampledepot.com/egs/java.util/coll_SortArray.html) to sort your data, and then check for duplicates.

You use value 0-10 so you can save your value in boolean array and it that way verify if this is duplicate or not:
boolean[] checker = new boolean[11];
for (int i =0; i < 50; i++) {
customers[i] = (int)((Math.random()*10000)%10+1);
if (checker[customers[i]]) {
System.out.println("yup"); //duplication
} else {
checker[customers[i]] = true;
}
}

You can use the below code if you are working with Integer array:
public class DuplicateInteger {
private static int countDuplicate;
public static int[] getDuplicateIntegers(int[] integerArray){
int duplicateIntegers[] = new int[integerArray.length];
countDuplicate = 0;
for(int i=0;i<integerArray.length;i++){
for(int j=i+1;j<integerArray.length;j++){
int replicaTest = 0;
if(integerArray[i]==integerArray[j]){
for(int k=0;k<countDuplicate;k++){
if(duplicateIntegers[k]==integerArray[i]){
replicaTest = 1;
}
}
if(replicaTest==0){
duplicateIntegers[countDuplicate] = integerArray[i];
countDuplicate++;
}
}
}
}
return duplicateIntegers;
}
public static void printDuplicateIntegers(int[] duplicateIntegers){
System.out.println("Duplicate Integers:");
System.out.println("-------------------");
for(int i=0;i<countDuplicate;i++){
System.out.println(duplicateIntegers[i]);
}
}
public static void main(String[] args){
int numberArray[] = {1, 2, 3, 4, 5, 6, 7, 1, 3, 5, 7};
printDuplicateIntegers(getDuplicateIntegers(numberArray));
}
}

Related

I have some code that prints out the summary of a given array but want to know how to print the position rather than the value inside the sum?

import java.util.ArrayList;
import java.util.Arrays;
public class SumSet {
static void sum_up_recursive(ArrayList<Integer> numbers, int target, ArrayList<Integer> partial) {
int s = 0;
for (int x : partial) {
s += x;
}
if (s == target) {
System.out.println("sum(" + Arrays.toString(partial.toArray()) + ")=" + target);
}
else if (s >= target) {
return;
}
for (int i = 0; i < numbers.size(); i++) {
ArrayList<Integer> remaining = new ArrayList<>();
int n = numbers.get(i);
for (int j = i + 1; j < numbers.size(); j++) {
remaining.add(numbers.get(j));
}
ArrayList<Integer> partial_rec = new ArrayList<>(partial);
partial_rec.add(n);
sum_up_recursive(remaining, target, partial_rec);
}
}
static void sum_up(ArrayList<Integer> numbers, int target) {
sum_up_recursive(numbers, target, new ArrayList<>());
}
public static void main(String[] args) {
Integer[] numbers = { 5, 5, 10, 15 };
int target = 15;
sum_up(new ArrayList<>(Arrays.asList(numbers)), target);
}
}
The current output is:
sum([5, 10])=15
sum([5, 10])=15
sum([15])=15
I am trying to figure out how to get the output to print the position of the array:
sum([3]) = 15
sum([0,3)] = 15
sum([1,3)]=15
If I understand your question correctly you want to print the position in the original list, right?
In that case I'd suggest you use a custom element type, e.g. something like this:
class PositionalElement {
final int position;
final int value;
public PositionalElement( int pos, int val ) {
position = pos;
value = val;
}
}
and
int[] numbers = new int[] {5,5,10,15};
List<PositionalElement> elements = new ArrayList<>();
for( int i = 0; i < numbers.length; i++ ) {
elements.add( new PositionalElement( i, numbers[i] ) );
}
That way, when printing your output you're free to either use value and/or position of each element.

How can I find the mode of a number in an array? [duplicate]

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
how can I write a method and return 7?
I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].
Try this answer. First, the data:
int[] a = {1,2,3,4,5,6,7,7,7,7};
Here, we build a map counting the number of times each number appears:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count+1 : 1);
}
Now, we find the number with the maximum frequency and return it:
Integer popular = Collections.max(map.entrySet(),
new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}).getKey();
As you can see, the most popular number is seven:
System.out.println(popular);
> 7
EDIT
Here's my answer without using maps, lists, etc. and using only arrays; although I'm sorting the array in-place. It's O(n log n) complexity, better than the O(n^2) accepted solution.
public int findPopular(int[] a) {
if (a == null || a.length == 0)
return 0;
Arrays.sort(a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] == previous)
count++;
else {
if (count > maxCount) {
popular = a[i-1];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
return count > maxCount ? a[a.length-1] : popular;
}
public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
Take a map to map element - > count
Iterate through array and process the map
Iterate through map and find out the popular
Assuming your array is sorted (like the one you posted) you could simply iterate over the array and count the longest segment of elements, it's something like #narek.gevorgyan's post but without the awfully big array, and it uses the same amount of memory regardless of the array's size:
private static int getMostPopularElement(int[] a){
int counter = 0, curr, maxvalue, maxcounter = -1;
maxvalue = curr = a[0];
for (int e : a){
if (curr == e){
counter++;
} else {
if (counter > maxcounter){
maxcounter = counter;
maxvalue = curr;
}
counter = 0;
curr = e;
}
}
if (counter > maxcounter){
maxvalue = curr;
}
return maxvalue;
}
public static void main(String[] args) {
System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}
If the array is not sorted, sort it with Arrays.sort(a);
Using Java 8 Streams
int data[] = { 1, 5, 7, 4, 6, 2, 0, 1, 3, 2, 2 };
Map<Integer, Long> count = Arrays.stream(data)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), counting()));
int max = count.entrySet().stream()
.max((first, second) -> {
return (int) (first.getValue() - second.getValue());
})
.get().getKey();
System.out.println(max);
Explanation
We convert the int[] data array to boxed Integer Stream. Then we collect by groupingBy on the element and use a secondary counting collector for counting after the groupBy.
Finally we sort the map of element -> count based on count again by using a stream and lambda comparator.
This one without maps:
public class Main {
public static void main(String[] args) {
int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
System.out.println(getMostPopularElement(a));
}
private static int getMostPopularElement(int[] a) {
int maxElementIndex = getArrayMaximumElementIndex(a);
int[] b = new int[a[maxElementIndex] + 1]
for (int i = 0; i < a.length; i++) {
++b[a[i]];
}
return getArrayMaximumElementIndex(b);
}
private static int getArrayMaximumElementIndex(int[] a) {
int maxElementIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[maxElementIndex]) {
maxElementIndex = i;
}
}
return maxElementIndex;
}
}
You only have to change some code if your array can have elements which are < 0.
And this algorithm is useful when your array items are not big numbers.
If you don't want to use a map, then just follow these steps:
Sort the array (using Arrays.sort())
Use a variable to hold the most popular element (mostPopular), a variable to hold its number of occurrences in the array (mostPopularCount), and a variable to hold the number of occurrences of the current number in the iteration (currentCount)
Iterate through the array. If the current element is the same as mostPopular, increment currentCount. If not, reset currentCount to 1. If currentCount is > mostPopularCount, set mostPopularCount to currentCount, and mostPopular to the current element.
Seems like you are looking for the Mode value (Statistical Mode) , have a look at Apache's Docs for Statistical functions.
package frequent;
import java.util.HashMap;
import java.util.Map;
public class Frequent_number {
//Find the most frequent integer in an array
public static void main(String[] args) {
int arr[]= {1,2,3,4,3,2,2,3,3};
System.out.println(getFrequent(arr));
System.out.println(getFrequentBySorting(arr));
}
//Using Map , TC: O(n) SC: O(n)
static public int getFrequent(int arr[]){
int ans=0;
Map<Integer,Integer> m = new HashMap<>();
for(int i:arr){
if(m.containsKey(i)){
m.put(i, m.get(i)+1);
}else{
m.put(i, 1);
}
}
int maxVal=0;
for(Integer in: m.keySet()){
if(m.get(in)>maxVal){
ans=in;
maxVal = m.get(in);
}
}
return ans;
}
//Sort the array and then find it TC: O(nlogn) SC: O(1)
public static int getFrequentBySorting(int arr[]){
int current=arr[0];
int ansCount=0;
int tempCount=0;
int ans=current;
for(int i:arr){
if(i==current){
tempCount++;
}
if(tempCount>ansCount){
ansCount=tempCount;
ans=i;
}
current=i;
}
return ans;
}
}
Array elements value should be less than the array length for this one:
public void findCounts(int[] arr, int n) {
int i = 0;
while (i < n) {
if (arr[i] <= 0) {
i++;
continue;
}
int elementIndex = arr[i] - 1;
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
arr[elementIndex] = -1;
}
else {
arr[elementIndex]--;
arr[i] = 0;
i++;
}
}
Console.WriteLine("Below are counts of all elements");
for (int j = 0; j < n; j++) {
Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
}
}
Time complexity of this will be O(N) and space complexity will be O(1).
import java.util.Scanner;
public class Mostrepeatednumber
{
public static void main(String args[])
{
int most = 0;
int temp=0;
int count=0,tempcount;
Scanner in=new Scanner(System.in);
System.out.println("Enter any number");
int n=in.nextInt();
int arr[]=new int[n];
System.out.print("Enter array value:");
for(int i=0;i<=n-1;i++)
{
int n1=in.nextInt();
arr[i]=n1;
}
//!!!!!!!! user input concept closed
//logic can be started
for(int j=0;j<=n-1;j++)
{
temp=arr[j];
tempcount=0;
for(int k=1;k<=n-1;k++)
{
if(temp==arr[k])
{
tempcount++;
}
if(count<tempcount)
{
most=arr[k];
count=tempcount;
}
}
}
System.out.println(most);
}
}
Best approach will be using map where key will be element and value will be the count of each element. Along with that keep an array of size that will contain the index of most popular element . Populate this array while map construction itself so that we don't have to iterate through map again.
Approach 2:-
If someone want to go with two loop, here is the improvisation from accepted answer where we don't have to start second loop from one every time
public class TestPopularElements {
public static int getPopularElement(int[] a) {
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++) {
temp = a[i];
tempCount = 0;
for (int j = i+1; j < a.length; j++) {
if (temp == a[j])
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void main(String[] args) {
int a[] = new int[] {1,2,3,4,5,6,2,7,7,7};
System.out.println("count is " +getPopularElement(a));
}
}
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
public static int getMostCommonElement(int[] array) {
Arrays.sort(array);
int frequency = 1;
int biggestFrequency = 1;
int mostCommonElement = 0;
for(int i=0; i<array.length-1; i++) {
frequency = (array[i]==array[i+1]) ? frequency+1 : 1;
if(frequency>biggestFrequency) {
biggestFrequency = frequency;
mostCommonElement = array[i];
}
}
return mostCommonElement;
}
Mine Linear O(N)
Using map to save all the differents elements found in the array and saving the number of times ocurred, then just getting the max from the map.
import java.util.HashMap;
import java.util.Map;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class MosftOftenNumber {
// for O(N) + map O(1) = O(N)
public static int mostOftenNumber(int[] a)
{
final Map m = new HashMap<Integer,Integer>();
int max = 0;
int element = 0;
for (int i=0; i<a.length; i++){
//initializing value for the map the value will have the counter of each element
//first time one new number its found will be initialize with zero
if (m.get(a[i]) == null)
m.put(a[i],0);
//save each value from the array and increment the count each time its found
m.put(a[i] , (Integer) m.get(a[i]) + 1);
//check the value from each element and comparing with max
if ( (Integer) m.get(a[i]) > max){
max = (Integer) m.get(a[i]);
element = a[i];
}
}
System.out.println("Times repeated: " + max);
return element;
}
public static int mostOftenNumberWithLambdas(int[] a)
{
Integer max = IntStream.of(a).boxed().max(Integer::compareTo).get();
Integer coumtMax = Math.toIntExact(IntStream.of(a).boxed().filter(number -> number.equals(max)).count());
System.out.println("Times repeated: " + coumtMax);
return max;
}
public static void main(String args[]) {
// int[] array = {1,1,2,1,1};
// int[] array = {2,2,1,2,2};
int[] array = {1,2,3,4,5,6,7,7,7,7};
System.out.println("Most often number with loops: " + mostOftenNumber(array));
System.out.println("Most often number with lambdas: " + mostOftenNumberWithLambdas(array));
}
}
Solution 1: Hashmap: O(n)
def most_freq_elem(arr):
frequency = {}
most_frequent, most_count = -1, 0
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
if frequency[num] > most_count:
most_count = frequency[num]
most_frequent = num
return most_frequent
Solution 2: Hashmap + Max: O(n)
def most_freq_elem(arr):
frequency = {}
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
return max(frequency, key=frequency.get)
public static void main(String[] args) {
int[] myArray = {1,5,4,4,22,4,9,4,4,8};
Map<Integer,Integer> arrayCounts = new HashMap<>();
Integer popularCount = 0;
Integer popularValue = 0;
for(int i = 0; i < myArray.length; i++) {
Integer count = arrayCounts.get(myArray[i]);
if (count == null) {
count = 0;
}
arrayCounts.put(myArray[i], count == 0 ? 1 : ++count);
if (count > popularCount) {
popularCount = count;
popularValue = myArray[i];
}
}
System.out.println(popularValue + " --> " + popularCount);
}
below code can be put inside a main method
// TODO Auto-generated method stub
Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
Set<Integer> set = new HashSet<Integer>(list);
int highestSeq = 0;
int seq = 0;
for (int i : set) {
int tempCount = 0;
for (int l : list) {
if (i == l) {
tempCount = tempCount + 1;
}
if (tempCount > highestSeq) {
highestSeq = tempCount;
seq = i;
}
}
}
System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);
public class MostFrequentIntegerInAnArray {
public static void main(String[] args) {
int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1};
System.out.println("Most common item = "+getMostFrequentInt(items));
}
//Time Complexity = O(N)
//Space Complexity = O(N)
public static int getMostFrequentInt(int[] items){
Map<Integer, Integer> itemsMap = new HashMap<Integer, Integer>(items.length);
for(int item : items){
if(!itemsMap.containsKey(item))
itemsMap.put(item, 1);
else
itemsMap.put(item, itemsMap.get(item)+1);
}
int maxCount = Integer.MIN_VALUE;
for(Entry<Integer, Integer> entry : itemsMap.entrySet()){
if(entry.getValue() > maxCount)
maxCount = entry.getValue();
}
return maxCount;
}
}
int largest = 0;
int k = 0;
for (int i = 0; i < n; i++) {
int count = 1;
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
count++;
}
}
if (count > largest) {
k = a[i];
largest = count;
}
}
So here n is the length of the array, and a[] is your array.
First, take the first element and check how many times it is repeated and increase the counter (count) as to see how many times it occurs.
Check if this maximum number of times that a number has so far occurred if yes, then change the largest variable (to store the maximum number of repetitions) and if you would like to store the variable as well, you can do so in another variable (here k).
I know this isn't the fastest, but definitely, the easiest way to understand
import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
public static void main(String [] args){
int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
Map map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < arrayToCheckFrom.length; i++){
int sum = 0;
for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
sum += 1;
}
map.put(arrayToCheckFrom[i], sum);
}
System.out.println(getMaxValue(map));
}
public static Integer getMaxValue( Map<Integer,Integer> map){
Map.Entry<Integer,Integer> maxEntry = null;
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
maxEntry = pair;
}
}
return maxEntry.getKey();
}
}
Comparing two arrays, I Hope for that this is useful for you.
public static void main(String []args){
int primerArray [] = {1,2,1,3,5};
int arrayTow [] = {1,6,7,8};
int numberMostRepetly = validateArrays(primerArray,arrayTow);
System.out.println(numberMostRepetly);
}
public static int validateArrays(int primerArray[], int arrayTow[]){
int numVeces = 0;
for(int i = 0; i< primerArray.length; i++){
for(int c = i+1; c < primerArray.length; c++){
if(primerArray[i] == primerArray[c]){
numVeces = primerArray[c];
// System.out.println("Numero que mas se repite");
//System.out.println(numVeces);
}
}
for(int a = 0; a < arrayTow.length; a++){
if(numVeces == arrayTow[a]){
// System.out.println(numVeces);
return numVeces;
}
}
}
return 0;
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MostOccuringEleementInArrayOfIntegers {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 4, 5, 3, 2, 1, 6, 7, 1, 2, 3, 2 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : arr) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
int max = 1;
int mostFrequent = 1;
for (Entry<Integer, Integer> e : map.entrySet()) {
// Swapping of the elements who is occuring most
if (e.getValue() > max) {
mostFrequent = e.getKey();
max = e.getValue();
}
}
// Print most frequent element
System.out.println("Most frequent element: " + mostFrequent);
}
}
public class MostFrequentNumber {
public MostFrequentNumber() {
}
int frequentNumber(List<Integer> list){
int popular = 0;
int holder = 0;
for(Integer number: list) {
int freq = Collections.frequency(list,number);
if(holder < freq){
holder = freq;
popular = number;
}
}
return popular;
}
public static void main(String[] args){
int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};
List<Integer> list = new ArrayList<Integer>();
for(Integer num : numbers){
list.add(num);
}
MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();
System.out.println(mostFrequentNumber.frequentNumber(list));
}
}
You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.
Second largest element:
Let us take example : [1,5,4,2,3] in this case,
Second largest element will be 4.
Sort the Array in descending order, once the sort done output will be
A = [5,4,3,2,1]
Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.
private static int getMostOccuringElement(int[] A) {
Map occuringMap = new HashMap();
//count occurences
for (int i = 0; i < A.length; i++) {
if (occuringMap.get(A[i]) != null) {
int val = occuringMap.get(A[i]) + 1;
occuringMap.put(A[i], val);
} else {
occuringMap.put(A[i], 1);
}
}
//find maximum occurence
int max = Integer.MIN_VALUE;
int element = -1;
for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
element = entry.getKey();
}
}
return element;
}
I hope this helps.
public class Ideone {
public static void main(String[] args) throws java.lang.Exception {
int[] a = {1,2,3,4,5,6,7,7,7};
int len = a.length;
System.out.println(len);
for (int i = 0; i <= len - 1; i++) {
while (a[i] == a[i + 1]) {
System.out.println(a[i]);
break;
}
}
}
}
This is the wrong syntax. When you create an anonymous array you MUST NOT give its size.
When you write the following code :
new int[] {1,23,4,4,5,5,5};
You are here creating an anonymous int array whose size will be determined by the number of values that you provide in the curly braces.
You can assign this a reference as you have done, but this will be the correct syntax for the same :-
int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};
Now, just Sysout with proper index position:
System.out.println(a[7]);

find the most popular element in int array in java array {2,3,4,2,3,3,2,9,5} [duplicate]

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
how can I write a method and return 7?
I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].
Try this answer. First, the data:
int[] a = {1,2,3,4,5,6,7,7,7,7};
Here, we build a map counting the number of times each number appears:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count+1 : 1);
}
Now, we find the number with the maximum frequency and return it:
Integer popular = Collections.max(map.entrySet(),
new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}).getKey();
As you can see, the most popular number is seven:
System.out.println(popular);
> 7
EDIT
Here's my answer without using maps, lists, etc. and using only arrays; although I'm sorting the array in-place. It's O(n log n) complexity, better than the O(n^2) accepted solution.
public int findPopular(int[] a) {
if (a == null || a.length == 0)
return 0;
Arrays.sort(a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] == previous)
count++;
else {
if (count > maxCount) {
popular = a[i-1];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
return count > maxCount ? a[a.length-1] : popular;
}
public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
Take a map to map element - > count
Iterate through array and process the map
Iterate through map and find out the popular
Assuming your array is sorted (like the one you posted) you could simply iterate over the array and count the longest segment of elements, it's something like #narek.gevorgyan's post but without the awfully big array, and it uses the same amount of memory regardless of the array's size:
private static int getMostPopularElement(int[] a){
int counter = 0, curr, maxvalue, maxcounter = -1;
maxvalue = curr = a[0];
for (int e : a){
if (curr == e){
counter++;
} else {
if (counter > maxcounter){
maxcounter = counter;
maxvalue = curr;
}
counter = 0;
curr = e;
}
}
if (counter > maxcounter){
maxvalue = curr;
}
return maxvalue;
}
public static void main(String[] args) {
System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}
If the array is not sorted, sort it with Arrays.sort(a);
Using Java 8 Streams
int data[] = { 1, 5, 7, 4, 6, 2, 0, 1, 3, 2, 2 };
Map<Integer, Long> count = Arrays.stream(data)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), counting()));
int max = count.entrySet().stream()
.max((first, second) -> {
return (int) (first.getValue() - second.getValue());
})
.get().getKey();
System.out.println(max);
Explanation
We convert the int[] data array to boxed Integer Stream. Then we collect by groupingBy on the element and use a secondary counting collector for counting after the groupBy.
Finally we sort the map of element -> count based on count again by using a stream and lambda comparator.
This one without maps:
public class Main {
public static void main(String[] args) {
int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
System.out.println(getMostPopularElement(a));
}
private static int getMostPopularElement(int[] a) {
int maxElementIndex = getArrayMaximumElementIndex(a);
int[] b = new int[a[maxElementIndex] + 1]
for (int i = 0; i < a.length; i++) {
++b[a[i]];
}
return getArrayMaximumElementIndex(b);
}
private static int getArrayMaximumElementIndex(int[] a) {
int maxElementIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[maxElementIndex]) {
maxElementIndex = i;
}
}
return maxElementIndex;
}
}
You only have to change some code if your array can have elements which are < 0.
And this algorithm is useful when your array items are not big numbers.
If you don't want to use a map, then just follow these steps:
Sort the array (using Arrays.sort())
Use a variable to hold the most popular element (mostPopular), a variable to hold its number of occurrences in the array (mostPopularCount), and a variable to hold the number of occurrences of the current number in the iteration (currentCount)
Iterate through the array. If the current element is the same as mostPopular, increment currentCount. If not, reset currentCount to 1. If currentCount is > mostPopularCount, set mostPopularCount to currentCount, and mostPopular to the current element.
Seems like you are looking for the Mode value (Statistical Mode) , have a look at Apache's Docs for Statistical functions.
package frequent;
import java.util.HashMap;
import java.util.Map;
public class Frequent_number {
//Find the most frequent integer in an array
public static void main(String[] args) {
int arr[]= {1,2,3,4,3,2,2,3,3};
System.out.println(getFrequent(arr));
System.out.println(getFrequentBySorting(arr));
}
//Using Map , TC: O(n) SC: O(n)
static public int getFrequent(int arr[]){
int ans=0;
Map<Integer,Integer> m = new HashMap<>();
for(int i:arr){
if(m.containsKey(i)){
m.put(i, m.get(i)+1);
}else{
m.put(i, 1);
}
}
int maxVal=0;
for(Integer in: m.keySet()){
if(m.get(in)>maxVal){
ans=in;
maxVal = m.get(in);
}
}
return ans;
}
//Sort the array and then find it TC: O(nlogn) SC: O(1)
public static int getFrequentBySorting(int arr[]){
int current=arr[0];
int ansCount=0;
int tempCount=0;
int ans=current;
for(int i:arr){
if(i==current){
tempCount++;
}
if(tempCount>ansCount){
ansCount=tempCount;
ans=i;
}
current=i;
}
return ans;
}
}
Array elements value should be less than the array length for this one:
public void findCounts(int[] arr, int n) {
int i = 0;
while (i < n) {
if (arr[i] <= 0) {
i++;
continue;
}
int elementIndex = arr[i] - 1;
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
arr[elementIndex] = -1;
}
else {
arr[elementIndex]--;
arr[i] = 0;
i++;
}
}
Console.WriteLine("Below are counts of all elements");
for (int j = 0; j < n; j++) {
Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
}
}
Time complexity of this will be O(N) and space complexity will be O(1).
import java.util.Scanner;
public class Mostrepeatednumber
{
public static void main(String args[])
{
int most = 0;
int temp=0;
int count=0,tempcount;
Scanner in=new Scanner(System.in);
System.out.println("Enter any number");
int n=in.nextInt();
int arr[]=new int[n];
System.out.print("Enter array value:");
for(int i=0;i<=n-1;i++)
{
int n1=in.nextInt();
arr[i]=n1;
}
//!!!!!!!! user input concept closed
//logic can be started
for(int j=0;j<=n-1;j++)
{
temp=arr[j];
tempcount=0;
for(int k=1;k<=n-1;k++)
{
if(temp==arr[k])
{
tempcount++;
}
if(count<tempcount)
{
most=arr[k];
count=tempcount;
}
}
}
System.out.println(most);
}
}
Best approach will be using map where key will be element and value will be the count of each element. Along with that keep an array of size that will contain the index of most popular element . Populate this array while map construction itself so that we don't have to iterate through map again.
Approach 2:-
If someone want to go with two loop, here is the improvisation from accepted answer where we don't have to start second loop from one every time
public class TestPopularElements {
public static int getPopularElement(int[] a) {
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++) {
temp = a[i];
tempCount = 0;
for (int j = i+1; j < a.length; j++) {
if (temp == a[j])
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void main(String[] args) {
int a[] = new int[] {1,2,3,4,5,6,2,7,7,7};
System.out.println("count is " +getPopularElement(a));
}
}
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
public static int getMostCommonElement(int[] array) {
Arrays.sort(array);
int frequency = 1;
int biggestFrequency = 1;
int mostCommonElement = 0;
for(int i=0; i<array.length-1; i++) {
frequency = (array[i]==array[i+1]) ? frequency+1 : 1;
if(frequency>biggestFrequency) {
biggestFrequency = frequency;
mostCommonElement = array[i];
}
}
return mostCommonElement;
}
Mine Linear O(N)
Using map to save all the differents elements found in the array and saving the number of times ocurred, then just getting the max from the map.
import java.util.HashMap;
import java.util.Map;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class MosftOftenNumber {
// for O(N) + map O(1) = O(N)
public static int mostOftenNumber(int[] a)
{
final Map m = new HashMap<Integer,Integer>();
int max = 0;
int element = 0;
for (int i=0; i<a.length; i++){
//initializing value for the map the value will have the counter of each element
//first time one new number its found will be initialize with zero
if (m.get(a[i]) == null)
m.put(a[i],0);
//save each value from the array and increment the count each time its found
m.put(a[i] , (Integer) m.get(a[i]) + 1);
//check the value from each element and comparing with max
if ( (Integer) m.get(a[i]) > max){
max = (Integer) m.get(a[i]);
element = a[i];
}
}
System.out.println("Times repeated: " + max);
return element;
}
public static int mostOftenNumberWithLambdas(int[] a)
{
Integer max = IntStream.of(a).boxed().max(Integer::compareTo).get();
Integer coumtMax = Math.toIntExact(IntStream.of(a).boxed().filter(number -> number.equals(max)).count());
System.out.println("Times repeated: " + coumtMax);
return max;
}
public static void main(String args[]) {
// int[] array = {1,1,2,1,1};
// int[] array = {2,2,1,2,2};
int[] array = {1,2,3,4,5,6,7,7,7,7};
System.out.println("Most often number with loops: " + mostOftenNumber(array));
System.out.println("Most often number with lambdas: " + mostOftenNumberWithLambdas(array));
}
}
Solution 1: Hashmap: O(n)
def most_freq_elem(arr):
frequency = {}
most_frequent, most_count = -1, 0
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
if frequency[num] > most_count:
most_count = frequency[num]
most_frequent = num
return most_frequent
Solution 2: Hashmap + Max: O(n)
def most_freq_elem(arr):
frequency = {}
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
return max(frequency, key=frequency.get)
public static void main(String[] args) {
int[] myArray = {1,5,4,4,22,4,9,4,4,8};
Map<Integer,Integer> arrayCounts = new HashMap<>();
Integer popularCount = 0;
Integer popularValue = 0;
for(int i = 0; i < myArray.length; i++) {
Integer count = arrayCounts.get(myArray[i]);
if (count == null) {
count = 0;
}
arrayCounts.put(myArray[i], count == 0 ? 1 : ++count);
if (count > popularCount) {
popularCount = count;
popularValue = myArray[i];
}
}
System.out.println(popularValue + " --> " + popularCount);
}
below code can be put inside a main method
// TODO Auto-generated method stub
Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
Set<Integer> set = new HashSet<Integer>(list);
int highestSeq = 0;
int seq = 0;
for (int i : set) {
int tempCount = 0;
for (int l : list) {
if (i == l) {
tempCount = tempCount + 1;
}
if (tempCount > highestSeq) {
highestSeq = tempCount;
seq = i;
}
}
}
System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);
public class MostFrequentIntegerInAnArray {
public static void main(String[] args) {
int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1};
System.out.println("Most common item = "+getMostFrequentInt(items));
}
//Time Complexity = O(N)
//Space Complexity = O(N)
public static int getMostFrequentInt(int[] items){
Map<Integer, Integer> itemsMap = new HashMap<Integer, Integer>(items.length);
for(int item : items){
if(!itemsMap.containsKey(item))
itemsMap.put(item, 1);
else
itemsMap.put(item, itemsMap.get(item)+1);
}
int maxCount = Integer.MIN_VALUE;
for(Entry<Integer, Integer> entry : itemsMap.entrySet()){
if(entry.getValue() > maxCount)
maxCount = entry.getValue();
}
return maxCount;
}
}
int largest = 0;
int k = 0;
for (int i = 0; i < n; i++) {
int count = 1;
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
count++;
}
}
if (count > largest) {
k = a[i];
largest = count;
}
}
So here n is the length of the array, and a[] is your array.
First, take the first element and check how many times it is repeated and increase the counter (count) as to see how many times it occurs.
Check if this maximum number of times that a number has so far occurred if yes, then change the largest variable (to store the maximum number of repetitions) and if you would like to store the variable as well, you can do so in another variable (here k).
I know this isn't the fastest, but definitely, the easiest way to understand
import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
public static void main(String [] args){
int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
Map map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < arrayToCheckFrom.length; i++){
int sum = 0;
for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
sum += 1;
}
map.put(arrayToCheckFrom[i], sum);
}
System.out.println(getMaxValue(map));
}
public static Integer getMaxValue( Map<Integer,Integer> map){
Map.Entry<Integer,Integer> maxEntry = null;
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
maxEntry = pair;
}
}
return maxEntry.getKey();
}
}
Comparing two arrays, I Hope for that this is useful for you.
public static void main(String []args){
int primerArray [] = {1,2,1,3,5};
int arrayTow [] = {1,6,7,8};
int numberMostRepetly = validateArrays(primerArray,arrayTow);
System.out.println(numberMostRepetly);
}
public static int validateArrays(int primerArray[], int arrayTow[]){
int numVeces = 0;
for(int i = 0; i< primerArray.length; i++){
for(int c = i+1; c < primerArray.length; c++){
if(primerArray[i] == primerArray[c]){
numVeces = primerArray[c];
// System.out.println("Numero que mas se repite");
//System.out.println(numVeces);
}
}
for(int a = 0; a < arrayTow.length; a++){
if(numVeces == arrayTow[a]){
// System.out.println(numVeces);
return numVeces;
}
}
}
return 0;
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class MostOccuringEleementInArrayOfIntegers {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 4, 5, 3, 2, 1, 6, 7, 1, 2, 3, 2 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : arr) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
int max = 1;
int mostFrequent = 1;
for (Entry<Integer, Integer> e : map.entrySet()) {
// Swapping of the elements who is occuring most
if (e.getValue() > max) {
mostFrequent = e.getKey();
max = e.getValue();
}
}
// Print most frequent element
System.out.println("Most frequent element: " + mostFrequent);
}
}
public class MostFrequentNumber {
public MostFrequentNumber() {
}
int frequentNumber(List<Integer> list){
int popular = 0;
int holder = 0;
for(Integer number: list) {
int freq = Collections.frequency(list,number);
if(holder < freq){
holder = freq;
popular = number;
}
}
return popular;
}
public static void main(String[] args){
int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};
List<Integer> list = new ArrayList<Integer>();
for(Integer num : numbers){
list.add(num);
}
MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();
System.out.println(mostFrequentNumber.frequentNumber(list));
}
}
You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.
Second largest element:
Let us take example : [1,5,4,2,3] in this case,
Second largest element will be 4.
Sort the Array in descending order, once the sort done output will be
A = [5,4,3,2,1]
Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.
private static int getMostOccuringElement(int[] A) {
Map occuringMap = new HashMap();
//count occurences
for (int i = 0; i < A.length; i++) {
if (occuringMap.get(A[i]) != null) {
int val = occuringMap.get(A[i]) + 1;
occuringMap.put(A[i], val);
} else {
occuringMap.put(A[i], 1);
}
}
//find maximum occurence
int max = Integer.MIN_VALUE;
int element = -1;
for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
element = entry.getKey();
}
}
return element;
}
I hope this helps.
public class Ideone {
public static void main(String[] args) throws java.lang.Exception {
int[] a = {1,2,3,4,5,6,7,7,7};
int len = a.length;
System.out.println(len);
for (int i = 0; i <= len - 1; i++) {
while (a[i] == a[i + 1]) {
System.out.println(a[i]);
break;
}
}
}
}
This is the wrong syntax. When you create an anonymous array you MUST NOT give its size.
When you write the following code :
new int[] {1,23,4,4,5,5,5};
You are here creating an anonymous int array whose size will be determined by the number of values that you provide in the curly braces.
You can assign this a reference as you have done, but this will be the correct syntax for the same :-
int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};
Now, just Sysout with proper index position:
System.out.println(a[7]);

Code compiles and executes, but does not print anything

The time-limit-extended is the status when executing the successfully compiled class file of the following code.
import java.io.*;
public class CandidateCode {
public static int ThirstyCrowProblem(int[] input1, int input2, int input3) {
int[] arrK = new int[input3];
int minstones = 0;
for (int i = 0; i < input3; i++) //create an array of k Os.
{
int smallest = input1[0], place = 0;
for (int j = 0; j < input2; j++) {
if ((smallest >= input1[j]) && (input1[j] >= 0)) {
smallest = input1[j];
place = j;
}
}
input1[place] = -1;
arrK[i] = smallest;
}
int n = input2, i = 0;
while (i < input3)
minstones = minstones + arrK[i] * (n - i);
return minstones;
}
public static void main(String[] args) {
int[] arr = new int[] {
5, 58
};
int stones_min = CandidateCode.ThirstyCrowProblem(arr, 2, 1);
System.out.println("The result is" + stones_min);
}
}
The cursor is waiting and waiting, but I don't think there is an error in the code!??
Option A :
Change your while into an if statement :
if(i<input3) {
minstones= minstones + arrK[i]*(n-i);
}
Option B : or increment i (i++) but I don't this that's what you want
while(i<input3) {
minstones = minstones + arrK[i]*(n-i);
i++;
}
You need to increment i in your while loop.Since you are not incrementing,its going in infinite loop.
while(i<input3)
{
minstones= minstones + arrK[i]*(n-i);
i++;
}
After making this change,I got
The result is10

Finding non duplicate element in an array

I am stuck in the following program:
I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.
So far I did the following:
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j)
//System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
Restricting the solution in array is preferable. Avoid using collections,maps.
public class NonRepeatingElement {
public static void main(String[] args) {
int result =0;
int []arr={3,4,5,3,4,5,6};
for(int i:arr)
{
result ^=i;
}
System.out.println("Result is "+result);
}
}
Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:
Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.
From Above here is the none duplicated example in Apple swift 2.0
func noneDuplicated(){
let arr = [1,4,3,7,3]
let size = arr.count
var temp = 0
for i in 0..<size{
var flag = true
temp = arr[i]
for j in 0..<size{
if(temp == arr[j]){
if(i != j){
flag = false
break
}
}
}
if(flag == true){
print(temp + " ,")
}
}
}
// output : 1 , 4 ,7
// this will print each none duplicated
/// for duplicate array
static void duplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
/*
for array of non duplicate elements in array just change int k=j+1; to int k = 0; in for loop
*/
static void NonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =0 ;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
public class DuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
duplicateItem(a);
NonDuplicateItem(a);
}
/// for first non repeating element in array ///
static void FirstNonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
//int k;
for(int k =0; k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
break;
}
count = 0;
}
}
public class NonDuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
FirstNonDuplicateItem(a);
}
I have a unique answer, it basically takes the current number that you have in the outer for loop for the array and times it by itself (basically the number to the power of 2). Then it goes through and every time it sees the number isn't equal to double itself test if its at the end of the array for the inner for loop, it is then a unique number, where as if it ever find a number equal to itself it then skips to the end of the inner for loop since we already know after one the number is not unique.
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int temp2 = 0;
int temp3 = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
temp2 = temp*temp;
for(int j=0;j<size;j++){
temp3 = temp*arr[j];
if(temp2==temp3 && i!=j)
j=arr.length
if(temp2 != temp3 && j==arr.length){
//System.out.println("Match found for "+temp);
flag = false;
result = temp;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
not tested but should work
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
int count=0;
for(int j=0;j<size;j++){
if(temp == arr[j]){
count++;
}
}
if (count==1){
result=temp;
break;
}
}
return result;
}
Try:
public class Answer{
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
int[] b =new int[a.length];
//instead of a.length initialize it to maximum element value in a; to avoid
//ArrayIndexOutOfBoundsException
for(int i=0;i<a.length;i++){
int x=a[i];
b[x]++;
}
for(int i=0;i<b.length;i++){
if(b[i]==1){
System.out.println(i); // outputs 2
break;
}
}
}
}
PS: I'm really new to java i usually code in C.
Thanks #dasblinkenlight...followed your method
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
boolean flag = true;
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j){
// System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
if(flag == true)
result = temp;
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
One disastrous mistake was not enclosing the content of if(i != j) inside braces. Thanks all for your answers.
If you are coding for learning then you can solve it with still more efficiently.
Sort the given array using merge sort of Quick Sort.
Running time will be nlogn.
The idea is to use Binary Search.
Till required element found All elements have first occurrence at even index (0, 2, ..) and next occurrence at odd index (1, 3, …).
After the required element have first occurrence at odd index and next occurrence at even index.
Using above observation you can solve :
a) Find the middle index, say ‘mid’.
b) If ‘mid’ is even, then compare arr[mid] and arr[mid + 1]. If both are same, then the required element after ‘mid’ else before mid.
c) If ‘mid’ is odd, then compare arr[mid] and arr[mid – 1]. If both are same, then the required element after ‘mid’ else before mid.
Another simple way to do so..
public static void main(String[] art) {
int a[] = { 11, 2, 3, 1,1, 6, 2, 5, 8, 3, 2, 11, 8, 4, 6 ,5};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
for (int j = 0; j < a.length; j++) {
if(j==0) {
if(a[j]!=a[j+1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(j==a.length-1) {
if(a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(a[j]!=a[j+1] && a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}
}
Happy Coding..
Using multiple loops the time complexity is O(n^2), So the effective way to resolve this using HashMap which in the time complexity of O(n). Please find my answer below,
`public static int nonRepeatedNumber(int[] A) {
Map<Integer, Integer> countMap = new HashMap<>();
int result = -1;
for (int i : A) {
if (!countMap.containsKey(i)) {
countMap.put(i, 1);
} else {
countMap.put(i, countMap.get(i) + 1);
}
}
Optional<Entry<Integer, Integer>> optionalEntry = countMap.entrySet().stream()
.filter(e -> e.getValue() == 1).findFirst();
return optionalEntry.isPresent() ? optionalEntry.get().getKey() : -1;
}
}`

Categories

Resources