Related
Question : Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
What exactly does the return statement do here. What does return i + 1 mean here ?
The return i + 1 is returning how many unique integers are there. I believe this is a Leetcode problem, and since its in place, the int[] is passed in by reference, Leetcode wants to know how many numbers to check (you're supposed to put the unique numbers in the first i + 1 spots).
If you look at the question, it says:
Which means that you return the length of the array.
So, if you have the array [1,1,2,3,4,4], you would turn that into [1,2,3,4,...], where the ... is the rest of the array. However, you return 4 because the length of the new array should be 4.
Hope this clears things up for you!
Your question has been already answered here; in addition to that, we can also start from zero and remove the first if statement:
Test with a b.java file:
import java.util.*;
class Solution {
public static final int removeDuplicates(
final int[] nums
) {
int i = 0;
for (int num : nums)
if (i == 0 || num > nums[i - 1]) {
nums[i++] = num;
}
return i;
}
}
class b {
public static void main(String[] args) {
System.out.println(new Solution().removeDuplicates(new int[] { 1, 1, 2}));
System.out.println(new Solution().removeDuplicates(new int[] { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4}));
}
}
prints
2
5
I tried in this easy way. Here Time complexity is O(n) and space
complexity: O(1).
static int removeDuplicates(int[] nums){
if(nums.length == 0) {
return 0;
}
int value = nums[0];
int lastIndex = 0;
int count = 1;
for (int i = 1; i < nums.length; i++) {
if(nums[i] > value) {
value = nums[i];
lastIndex = lastIndex+1;
nums[lastIndex] = value;
count++;
}
}
return count;
}
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
if (n == 0 || n == 1)
return n;
int j = 0;
for (int i=0; i<n-1; i++)
if (nums[i]!= nums[i+1])
nums[j++] = nums[i];
nums[j++]=nums[n-1];
return j;
}
}
public class RemoveDuplicateSortedArray {
//Remove Duplicates from Sorted Array
public static void main(String[] args) {
int[] intArray = new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
int count = extracted(intArray);
for (int i = 0; i < count; i++) {
System.out.println(intArray[i]);
}
}
private static int extracted(int[] intArray) {
int size = intArray.length;
int count = 1;
if (size == 1) {
return 1;
} else if (size == 2) {
if (intArray[0] == intArray[1]) {
return 1;
} else {
return 2;
}
} else {
for (int i = 0, j = i + 1; j < size; j++) {
if (intArray[i] < intArray[j]) {
i++;
intArray[i] = intArray[j];
count++;
}
}
return count;
}
}
}
I am trying to write code to display the even elements to even indexes and odd to odd indexes and if the numbers added numbers are same then add zeros accordingly.
Example:
x = [1,2,3,4]
output: 2 1 4 3
x = [1 1 1 4]
output: 4 1 0 1 0 1
I reached to get even and odd positions but stuck after that.
Below is my code.
import java.util.*;
class ArrayDemo3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Size of Array :: ");
int size = s.nextInt();
int[] x = new int[size];
System.out.println("Array Created having the size :: " + size);
System.out.println("Enter Elements for Array :: ");
for (int i = 0; i < size; i++) {
System.out.println("Enter element no-" + (i + 1) + " ::");
x[i] = s.nextInt();
}
System.out.println("Contents of Array ::");
for (int i = 0; i < size; i++) {
System.out.print(x[i] + " ");
}
for (int i = 0; i < size; i = i + 1) {
int even = 0;
int odd = 1;
if (i < size && x[i] % 2 == 0) {
System.out.print("even : ");
even = even + i;
System.out.print("position" + i + " " + x[i] + " ");
} else {
System.out.print("odd : ");
odd = odd + i;
System.out.print(i + " " + x[i] + " ");
}
if (even < size && odd < size) {
int temp = x[even];
x[even] = x[odd];
x[odd] = temp;
} else {
}
//System.out.print(x[i] + " ");
}
}
}
You can break up your problem in 3 parts:
First create two lists, one containing in encountered order the even numbers and the other the odd numbers:
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
Pad the shorter of the two lists with zeros (0s) to make it equal length as the other one:
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
Finally join intertwining both lists:
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
The following is the full working example:
public class ArrayRearrangement {
public static void main(String[] args) {
// int[] result = rearrange(1, 2, 3, 4);
int[] result = rearrange(1, 1, 1, 4);
System.out.println(Arrays.stream(result).boxed().collect(Collectors.toList()));
}
private static int[] rearrange(int... numbers) {
List<List<Integer>> numsByOddity = createOddityLists(numbers);
padShorterList(numsByOddity);
return joinLists(numsByOddity).stream().mapToInt(i->i).toArray();
}
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
}
Complete code on GitHub
Hope this helps.
Using arrays something like this we can do. Code needs to be optimised.
public static int[] arrangeInEvenOddOrder(int[] arr)
{
// Create odd and even arrays
int[] oddArr = new int[arr.length];
int[] evenArr = new int[arr.length];
int oCount = 0, eCount = 0;
// populate arrays even and odd
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
evenArr[eCount++] = arr[i];
else
oddArr[oCount++] = arr[i];
}
int[] resArr = new int[oCount >= eCount?
2*oCount : 2*eCount-1];
// populate elements upto min of the
// two arrays
for (int i =0; i < (oCount <= eCount?
2*oCount : 2*eCount ); i++ )
{
if( i%2 == 0)
resArr[i] = evenArr[i/2];
else
resArr[i] = oddArr[i/2];
}
// populate rest of elements of max array
// and add zeroes
if (eCount > oCount)
{
for (int i=2*oCount,j=0;i<2*eCount-1; i++)
{
if (i%2 == 0)
{
resArr[i] = evenArr[oCount+j];
j++;
}
else
resArr[i] = 0;
}
}
else if (eCount < oCount)
{
for (int i=2*eCount,j=0;i<2*oCount; i++)
{
if ( i%2 != 0)
{
resArr[i] = oddArr[eCount+j];
j++;
}
else
resArr[i] = 0;
}
}
return resArr;
}
Sort element based on index i.e if the element is even, it must be at even position and vise-versa
int sortArrayByEvenOddIndex(int arr[]) {
int n = arr.length;
int res[] = new int[n];
int odd = 1;
int even = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
res[even] = arr[i];
even += 2;
} else {
res[odd] = arr[i];
odd += 2;
}
}
return res;
}
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]);
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]);
The question is about Solving this problem from codingBat in Java.
Problem Statement:
Return an array that contains the exact same numbers as the given array, but rearranged so that all the even numbers come before all the odd numbers. Other than that, the numbers can be in any order. You may modify and return the given array, or make a new array.
evenOdd({1, 0, 1, 0, 0, 1, 1}) → {0, 0, 0, 1, 1, 1, 1}
evenOdd({3, 3, 2}) → {2, 3, 3}
evenOdd({2, 2, 2}) → {2, 2, 2}
The Problem is simple with 2 loops I attempted at solving it with 1 it got too lengthy I believe, is there any other efficient way to solve the above problem using 1 loop?
do not use collections!
My solution:
public int[] evenOdd(int[] nums) {
boolean oddFound=false;
int count=-1;
int oddGap=0;
for(int i=0;i<nums.length;i++)
{
if(!(oddFound)&(nums[i]%2==0))
continue;
if((!oddFound)&(nums[i]%2==1))
{
oddFound=true;
count=i;
continue;
}
if((oddFound)&(nums[i]%2==1))
{
oddGap++;
continue;
}
if((oddFound)&(nums[i]%2==0))
{
int temp=nums[count];
nums[count]=nums[i];
nums[i]=temp;
if(i>0)
i--;
if(oddGap>0)
{
oddGap--;
count+=1;
oddFound=true;
continue;
}
oddFound=false;
}
}
return nums;
}
Since creating a new array is allowed, and the order of the numbers is irrelevant, I would use the following approach:
public int[] evenOdd(int[] nums) {
int[] output = new int[nums.length];
int evenPos = 0;
int oddPos = nums.length-1;
for (int i : nums) {
if (i%2==0) {
output[evenPos++]=i;
} else {
output[oddPos--]=i;
}
}
return output;
}
Update: A somewhat less readable version that doesn't require an extra array (along the lines of what #Seelenvirtuose suggests, just without the extra loops)
public int[] evenOdd(int[] nums) {
int evenPos = 0;
int oddPos = nums.length-1;
while (true) {
if (evenPos>=oddPos || evenPos>=nums.length || oddPos<0) {
break;
}
if (nums[evenPos]%2==0) {
evenPos++;
}
if (nums[oddPos]%2!=0) {
oddPos--;
}
if (evenPos<oddPos && nums[evenPos]%2 != 0 && nums[oddPos]%2 == 0) {
int tmp = nums[evenPos];
nums[evenPos] = nums[oddPos];
nums[oddPos] = tmp;
oddPos--;
evenPos++;
}
}
return nums;
}
You do not need any temporary lists or array because you can reorder the elements in-situ.
This is a simple algorithm:
Define two pointers, left and right (initially set to the bounds of the array).
As long as left does not exceed right and nums[left] is even, increment left.
As long as right does not exceed left and nums[right] is odd, decrement right.
If left is still less than right, swap the elements at positions left and right.
Repeat 2,3,4 as long as left is still less than right.
Got it? Here some code:
public int[] evenOdd(int[] nums) {
// (1)
int left = 0;
int right = nums.length -1;
do {
// (2)
while (left < right && nums[left] % 2 == 0)
left += 1;
// (3)
while (right > left && nums[right] % 2 != 0)
right -= 1;
// (4)
if (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
} while (left < right); // (5)
return nums;
}
Okay! I finally jumped across this question which is actually closed but the solution by asker was almost there apart from failing in 2 cases which I fixed:
I commented out he code by asker which was making it fail in a couple of cases as seen in the question.
I think below is the simplest and most optimized solution:
public int[] evenOdd(int[] nums) {
int y=nums.length,x,a=0;
int temp=0;
for(x=0;x<y;x++)
{
if(nums[x]%2==0) {
if(a>(y-2))
return nums;
else{
//nums[a]=nums[a]+nums[x];
//nums[x]=nums[a]-nums[x];
//nums[a]=nums[a]-nums[x];
temp=nums[a];
nums[a]=nums[x];
nums[x]=temp;
a+=1;
}
}
return nums;
}
Traverse evenOdd from 0 to N.
for every even number encountered, copy it to the required position on the evenOdd array.
for every odd num encountered, store it in a separate array called oddnum.
After traversing the whole array, just copy the elements from oddnum to the Back of evenOdd.
Ex: evenOdd = {5,2,1,4}
Step 1. copy 5 to oddnum[0]
2. copy 2 to evenodd[0]
3. copy 1 to oddnum[1]
4. copy 1 to evenodd[1]
5. cpy oddnum[0] to evenOdd[2] and oddnum[1] to evenOdd[3]
Keeping to your restrictions, here's a one-loop answer:
public int[] evenOdd(int[] nums) {
int[] result = new int[nums.length];
int nextEven = 0;
int nextOdd = nums.length - 1;
for ( int num : nums )
{
if ( num % 2 == 0 )
result[ nextEven++ ] = num;
else
result[ nextOdd-- ] = num;
}
return result;
}
public int[] evenOdd(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
int temp = nums[i];
nums[i] = nums[count];
nums[count] = temp;
count++;
}
}
return nums;
}
public int[] evenOdd(int[] nums) {
Stack stack = new Stack();
int[] nums2 = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
if(nums[i] % 2 != 0) {
stack.push(nums[i]);
}
}
for(int i = 0; i < nums.length; i++) {
if(nums[i] % 2 == 0) {
stack.push(nums[i]);
}
}
for(int i = 0; i < nums.length; i++) {
nums2[i] = (Integer) stack.pop();
}
return nums2;
}
In-place version (stable):
We continually search for te first and last invalid values (first odd, before last even) and keep swapping them until they cross:
public int[] evenOdd(int[] nums) {
int first = 0, last = nums.length - 1;
while (first < last) {
while ((first < last) && isOdd(nums[last])) last--;
while ((first < last) && !isOdd(nums[first])) first++;
swap(nums, first, last);
}
return nums;
}
boolean isOdd(int num) { return (num & 1) == 1; }
void swap(int[] nums, int i, int j) {
int copy = nums[i];
nums[i] = nums[j];
nums[j] = copy;
}
With auxiliaries (stable):
We partition the even and odd values in separate lists and concatenate them back:
public int[] evenOdd(int[] nums) {
List<Integer> evens = new ArrayList<Integer>(nums.length);
List<Integer> odds = new ArrayList<Integer>(nums.length);
for (int num : nums)
if (isOdd(num)) odds.add(num);
else evens.add(num);
int[] results = new int[nums.length];
int i = 0;
for (int num : evens) results[i++] = num;
for (int num : odds) results[i++] = num;
return results;
}
boolean isOdd(int num) { return (num & 1) == 1; }
Simplified solution which uses Srteam API:
public int[] evenOdd(int[] nums) {
int[] evenOddArr = new int[nums.length];;
int[] evenArr = Arrays.stream(nums).filter(x -> x % 2 == 0).toArray();;
int[] oddArr = Arrays.stream(nums).filter(x -> x % 2 != 0).toArray();
evenOddArr = java.util.stream.IntStream.concat(Arrays.stream(evenArr), Arrays.stream(oddArr))
.toArray();
return evenOddArr;
}
It passes all the tests on CodingBat: