Ok so I'm trying to find the largest element in an array, and I realize this is not the best method to do this, it only works in some cases. Would appreciate some pointers on how to change my code so it works for all instances.
public static int maxArray(int[] a) {
int max = 0;
for (int j = 0; j < a.length-1; j++) {
if (a[j+1] > a[j]) {
max = a[j+1];
} else {
max = a[j];
}
}
return max;
}
I suggest you do it like so,
Start with max = a[0]; then loop with j from 1 to a.length.
Compare a[j] to max, that is if a[j] > max then set max = a[j];.
Use this method.
public static int maxArray(int[] a) {
int max = a[0]; // saves a bit of time
for (int j = 1; j < a.length; j++) {
if (a[j] > max) {
max = a[j];
}
}
return max;
}
This is pretty speedy and concise.
You need to compare the current element with maximum element, not with the next one.
if (a[j] > max) {
max = a[j];
}
In Java 8 You can use Stream:
public static int maxArray(int[] a) {
return Arrays.stream(a).max().getAsInt();
}
public static <T extends Object & Comparable<? super T>> T maxArray(T[] array) {
return Collections.max(Arrays.asList(array));
}
after you make calls to the function, eg:
Integer[] a = { 1, 5, -6, 3, 0, 2 };
Integer max = maxArray(a);
System.out.println(max);
public static int getMaxElement(int[] elements) {
int max = elements[0];
for (int j = 0; j < elements.length-1; j++) {
if (elements[j] > max) {
max = elements[j];
}
}
return max;
}
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'm trying to make a method than returns the second bigger number of an array.
When I return the value, in console appears 2 or more values. I can't understand why is this happening. Can somebody help me to understand this, please?
I did a method to search the bigger value so I can use it on the one which returns the second bigger.
public class ThirdMax {
public static int maxNum (int[] array) { //Returns the bigger value of the array.
int aux = 0; //Variable to store the bigger value found and compare it with the rest.
for (int i = 0; i < array.length; i++) {
if(array[i] > aux) { //If the actual value is bigger than the aux
aux = array[i]; //override the aux value with actual value.
}
}
System.out.println(aux);
return aux;
}
public static int secondMax(int[] array) { //Returns the second bigger value on the array.
int valorMax = maxNum(array); //Store the bigger value on a variable so we can use it later.
int valorMax2 = 0; //Variable to store the result.
int[] auxArray = new int [array.length];
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) { //When we get to the valorMax, we replace it in the array with a 0.
array[i] = 0;
} else {
auxArray[i] = array[i];
}
valorMax2 = maxNum(auxArray); //Search again the bigger value after the previous one is replaced by 0.
}
return valorMax2;
}
}
Thanks in advance for your time!
You call maxNum(auxArray); multiple times. Each of them prints a max value.
Hence you received multiple result.
To immediately resolve it, remove the print System.out.println(aux);
in your function.
And make only one print function right before you return
System.out.println(valorMax2);
return valorMax2;
But your code looks not good. It need multiple improvement.
To find the second biggest number, you only need to loop once like this:
public static int secondMax(int[] array) {
int max = Integer.MIN_VALUE; // Max value
int secondMax = Integer.MIN_VALUE; // Second max value, its our result
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
secondMax = max;
max = array[i];
} else if (array[i] > secondMax) {
secondMax = array[i];
}
}
return secondMax;
}
This looks OK, but can't extends to find n-th max number, because our if conditions will be very complex. Then you try to find max number once at a time:
// Return max number in array which is lower than ceilValue
// Return Integer.MIN_VALUE if no such value found
public static int maxValueBelow(int[] array, int ceilValue) {
int max = Integer.MIN_VALUE;
for (int i = 0; i<array.length; i++) {
if (array[i] < ceilValue && array[i] > max) {
max = array[i];
}
}
return max;
}
public static int findNthValue(int[] array) {
int maxValue = maxValueBelow(array, Integer.MAX_VALUE);
int secondMaxValue = maxValueBelow(array, maxValue);
int thirdMaxValue = maxValueBelow(array, secondMaxValue);
// You can improve this function by give it's a second parameter `n`, and use for loop to find the `n-th` max value.
}
Since you're setting the largest number to 0 you really don't need auxArray.
You also don't need a second valorMax.
You might want to refactor your code to the following.
public static int secondMax(int[] array) {
int valorMax = maxNum(array);
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) {
array[i] = 0;
}
}
return maxNum(array); // just return the result of maxNum(array)
}
be sure to remove the print statement from maxNum if you don't want your program to print 2 numbers to console.
Because you put get second max function in the wrong place.
public static int secondMax(int[] array) {
int valorMax = maxNum(array);
int valorMax2 = 0;
int[] auxArray = new int [array.length];
for (int i = 0; i < array.length; i++) {
if(array[i] == valorMax) {
array[i] = 0;
} else {
auxArray[i] = array[i];
}
}
valorMax2 = maxNum(auxArray); // this should be out of loop
return valorMax2;
}
}
My problem is that the selectionsort shows wrong number of swaps.
It always shows 0 or some large number.
When the array given is sorted, it always show a large number or all other unsorted tests are always 0.
//this class is called selectionSort. It sorts a given array.
public class SelectionSort implements ISorter {
private int swaps;
public SelectionSort() {}
#Override
public ISortStats sort(int[] a) {
long time = System.nanoTime();
int swapping = 0;
int numOfComparisons = 0;
for (int i = 0; i < a.length; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++) {
numOfComparisons++;
if (a[min] >= a[j]) {
min = j;
}
}
swapping = swap(a, i, min, this.swaps);
}
long endTime = System.nanoTime();
SortStats ss = new SortStats("Selection Sort",
a.length,
numOfComparisons,
swapping,
(endTime - time));
return ss;
}
private int swap(int[] a, int i, int j, int swapping) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
return swapping++;
}
}
I don't know why you have swaps as a class member, but this line is definitely wrong
swapping = swap(a, i, min, this.swaps);
As you are never updating this.swaps
public class SelectionSort implements ISorter {
private int swaps;
public SelectionSort(){
}
#Override
public ISortStats sort(int[] a) {
long time = System.nanoTime();
int swapping =0;
int numOfComparisons = 0;
for (int i=0; i<a.length; i++) {
int min = i;
for (int j=i+1; j < a.length; j++) {
numOfComparisons++;
if (a[min] >= a[j]) {
min = j;
}
}
swapping = swap(a, i, min, swapping);
}
long endTime = System.nanoTime();
SortStats ss = new SortStats("Selection Sort", a.length, numOfComparisons, swapping, (endTime -time));
return ss ;
}
private static int swap (int[] a, int i, int j, int swapping){
if(!(order(a))){
swapping++;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return swapping;
}
private static boolean order(int[] arr){
int count = 0;
//this loop runs thru the array to check if it is in order.
for(int a = 0; a < arr.length-1; a++){
if(arr[a] <= arr[a+1]){ // if true count plus 1
count++;
}
}
if(count == arr.length-1){ // checks if the count and arr length -1 is equal
return true; // if equal it will return true
}
return false; // returns false if the array is not correctly sorted.
}
}
So I'm writing a method to calculate mode of a sorted array. But when i print out the mode value, it always comes out as 0.00, and i tried to fix it but could't.
Here's my code for this method:
(numRead is the passed array, num is the array length that actually have values)
public static void modeCalc(double[] numRead, int num)
{
double maxValue = numRead[0];
int maxCount = 0;
for (int i = 0; i < numRead.length; i++)
{
int count = 0;
for (int j = 0; j < numRead.length; j++)
{
if (numRead[j] == numRead[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = numRead[i];
}
}
return maxValue;
}
Any help is much appreciated!
This should work. You need to return a double, and you need to use num.
class ModeArray
{
public static void main(String[] args) {
double[] numRead = { 1, 2, 3, 3, 4, 4, 4, 5, 0, 0, 0, 0, 0 };
System.out.println(modeCalc(numRead, 8));
}
public static double modeCalc(double[] numRead, int num) {
double maxValue = numRead[0];
int maxCount = 0;
for (int i = 0; i < num; i++) {
int count = 0;
for (int j = 0; j < num; j++) {
if (numRead[j] == numRead[i]){
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxValue = numRead[i];
}
}
return maxValue;
}
}
If you know the array is sorted, you should use this information.
public static double modeCalc(double[] numRead, int num) {
double maxValue = numRead[0];
double lastValue = maxValue;
int count = 1;
int maxCount = 1;
for (int i = 1; i < num; i++) {
if (numRead[i] == lastValue) {
count++;
} else {
count = 1;
lastValue = numRead[i];
}
if (count > maxCount) {
maxCount = count;
maxValue = lastValue;
}
}
return maxValue;
}
PS: Please don't use if-statement without braces. It makes it easier to add bugs, and harder to find them.
a cursory glance suggests that your array has more 0 values at the end of the sorted data and these become the mode. here is what appears to be the problem, it is stated that numRead is the sorted array, but it has only num values of significance. the loops search the array to the end, not for the number of elements that have good values. change numRead.length to num and see if that helps. also, try passing a full array (no empty elements) and see if it works any better. it is likely that the empty elements are initialized to zero and that there are more of these than any other value.
Trying to solve codility lessons for practice and working on this.
Written my code in Java and tested the code on a wide range of inputs, however the code fails for extreme_min_max, single and double in the codility test results.
Assumption given:
N is an integer within the range [1..100,000].
Each element of array A is an integer within the range [1..1,000,000,000].
Explanation of my code:
1. Sort the given array.
2. Iterate over each element in the array to find the difference between every consecutive pair. If the difference is not 1, Then its not a perm hence return 0. In case there is only one element in the array, return 1.
Can anyone please help me find out the bug(s) in my code?
My code:
public int solution(int[] A)
{
if(A.length == 1)
return 1;
Arrays.sort(A);
for (int i = 0; i < A.length-1; i++)
{
long diff = Math.abs(A[i] - A[i+1]);
if(diff!=1)
return 0;
}
return 1;
}
Here is simple and better implementation which runs in O(N) time complexity and takes O(N) space complexity.
public int solution(int[] A)
{
int size = A.length;
int hashArray[] = new int[size+1];
for (int i = 0; i < size; i++)
{
if(A[i]>size)
return 0;
else
hashArray[A[i]]+=1;
}
for(int i=1;i<=size;i++)
if(hashArray[i]!=1)
return 0;
return 1;
}
Try this in C# (Score 100%) :
using System;
using System.Linq;
class Solution {
public int solution(int[] A) {
if (A.Any(x => x == 0)) { return 0; }
var orderSelect = A.OrderBy(x => x).GroupBy(x => x);
if (orderSelect.Any(x => x.Count() > 1)) { return 0; }
var res = Enumerable.Range(1, A.Length).Except(A);
return res.Any() ? 0 : 1;
}
}
Pretty simple:
Your code doesn't check this condition:
A permutation is a sequence containing each element from 1 to N once, and only once.
Ensure that the first element after sorting is 1, and everything should work.
I'm not big on Java syntax, but what you want to do here is:
Create an array temp the length of A - initialized to 0.
Go over A and do temp[A[i]]++.
Go over temp, and if any place in the array is not 1, return false.
If duplicate exists - return 0 I have implemented with 100% pass
https://codility.com/demo/results/trainingWX2E92-ASF/
public static int permCheck(int A[]){
Set<Integer> bucket = new HashSet<Integer>();
int max = 0;
int sum=0;
for(int counter=0; counter<A.length; counter++){
if(max<A[counter]) max=A[counter];
if(bucket.add(A[counter])){
sum=sum+A[counter];
}
else{
return 0;
}
}
System.out.println(max+"->"+sum);
int expectedSum = (max*(max+1))/2;
if(expectedSum==sum)return 1;
return 0;
}
Here's my first 100% code.
I can't say if it's the fastest but it seems all correct -- watch the double OR ( || ) condition.
import java.util.Arrays;
class Solution
{
public int solution(int[] A)
{
int i = 0;
int size = A.length;
if ( size > 0 && size < 100001)
{
// Sort the array ascending:
Arrays.sort(A);
// Check each element:
for(i = 0; i < size; i++)
if ( A[i] > size || A[i] != (i + 1) )
return 0;
return 1;
}
return 0;
}
}
EDIT
Actually, we need not worry about valid first element data (i.e. A[i] > 0) because, after sorting, a valid perm array must have A[0] = 1 and this is already covered by the condition A[i] = i + 1.
The upper limit for array entries (> 1,000,000,000) is restricted further by the limit on the array size itself (100,000) and we must check for conformity here as there will be a Codility test for this. So I have removed the lower limit condition on array entries.
Below code runs and gave me a 100%, the time complexity is O(n):
private static int solution(int[] A) {
int isPermutation = 1; // all permutations start at 1
int n = A.length;
Arrays.sort(A);
if (n == 0) return 0; // takes care of edge case where an empty array is passed
for (int i = 0; i < n; i++) {
if (A[i] != isPermutation) { //if current array item is not equals to permutation, return 0;
return 0;
}
isPermutation++;
}
return 1;
}
100% score with complexity O(N)
public int solution(int[] A) {
int res = 1;
if (A.length == 1 && A[0]!=1)
return 0;
int[] B = new int[A.length];
for (int j : A) {
int p = j - 1;
if (A.length > p)
B[p] = j;
}
for (int i = 0; i < B.length - 1; i++) {
if (B[i] + 1 != B[i + 1]) {
res = 0;
break;
}
}
return res;
}