Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to solve a leetcode problem :
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
And I think I have the correct solution but I'm just not sure why I'm getting it incorrect.
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i > nums.length;i++) {
int j= i;
while ((j<nums.length) && (nums[j]==0)){
j++;
}
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
}
}
}
You can solve this problem O(N) with one pointer. This'd pass through:
public class Solution {
public static void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0)
return;
int pos = 0;
for (int num : nums)
if (num != 0)
nums[pos++] = num;
while (pos < nums.length)
nums[pos++] = 0;
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
The for loop isn't correct (has to be i < nums.length), also, your solution doesn't work if there is nothing to do:
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
yields in:
org.junit.ComparisonFailure: expected:<[[1, 2], 0, 0]> but was:<[[0, 0], 0, 0]>
Just write some test cases yourself and see what's wrong.
In your case:
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
is wrong because you're swapping i with j, even if i == j and nums[i] != 0.
Since I don't think you're asking for a working solution, I won't provide one. But here are my test cases:
#Test
public void testEmptyArray() {
int[] array = new int[0];
moveZeroes(array);
assertEquals(0,array.length);
}
#Test
public void testZeroOnlyArrays() {
int[] array = {0,0,0,0};
final String arrayString = Arrays.toString(array);
moveZeroes(array);
assertEquals(arrayString, Arrays.toString(array));;
}
#Test
public void mixedTest() {
int[] array = {0,1,0,2};
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
moveZeroes(array);
assertEquals(expectedString, Arrays.toString(array));;
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
}
The 'for' loop should be: for (int i = 0; i < nums.length;i++)
then, your loop will run on the array indexes from 0 until it reaches the length of the array.
The current code will not even enter the loop as you have defined i=0 and the loop condition is run the loop only if it is larger than the array size: (i > nums.length) which of course is not true
You are using i > nums.length that's why loop is not executed
You need an index for non-zero value. Here in my solution j is for non-zero value index means when you find a non-zero value set j index and increment it. If j is smaller than i or equal that's means there will be zero found then set it.
public void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[j] = nums[i];
j++;
}
if (j <= i) {
nums[i] = 0;
}
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Kindly help me with the underlying program as I am stuck. I'm a newbie programmer.
import java.util.*;
public class Source
{
static int maxProduct(int arr[]) {
int n = arr.length ;
if (n < 2)
{
System.out.println("NA");
return Integer.MIN_VALUE;
}
int a = arr[0];
int b = arr[1];
for(int i = 0; i<n; i++) {
for (int j = i+1; j<n; j++) {
if (arr[i]*arr[j] > arr[0]*arr[1]) {
a = arr[i];
b = arr[j];
}
}
}
return maxProduct;
}
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int[] arr = new int[size];
for(int i = 0; i < size; i++) {
arr[i] = s.nextInt();
}
int answer = maxProduct(arr);
System.out.print(answer);
}
}
You should change
if (arr[i]*arr[j] > arr[0]*arr[1])
to
if (arr[i]*arr[j] > a * b)
Since arr[0]*arr[1] is just the original max product, so you shouldn't be comparing against it.
Also note that your solution is not as efficient as it can be, since you are using a nested loop, which requires O(n^2) running time.
You can achieve linear (O(n)) running time if you use the fact that the max product is either the product of the two highest positive values or the product of the two lowest negative values. This means that if you find these 4 numbers, which can be done with a single loop, you'll find the max product.
I have an atomic integer array of size 10. I am using this array to organize numbers 1-10 sent in by threads. This 1-10 will eventually be able to change to be a range of numbers larger than 10 and the list is to contain the 10 greatest numbers in that range. I can see the numbers going into the loops and recognizing that they are greater than a number currently there. However, there is never more than 2 numbers in the array when it is printed out. I have tried to trace my code in debug mode, however, it looks as if it is working as intended to me. I feel like there may be a simple error to my logic? I am completely sure all values are entering in the function as I have triple checked this. I start at the end of the array which should contain the highest value and then swap downwards once the slot has been determined. I would appreciate the assistance. This is just a simple experiment I am doing in order to grasp the basics before I try to tackle a homework assignment.
Here an example of my code:
public class testing{
static AtomicIntegerArray maxList = new AtomicIntegerArray(10);
final static int n = 10;
static void setMax(int value)
{
for(int i = 9; i >= 0; i--)
{
if(value > maxList.get(i))
{
int temp = maxList.get(i);
maxList.set(i,value);
if(i == 0)
{
maxList.set(i, value);
}
else
{ for(int j = i-1; j > 0; j--)
{
maxList.set(j, temp);
temp = maxList.get(j-1);
}
}
break;
}
}
public static void main(String[] args)
{
for (int i = 0; i < n; i++)
{
setMax(i);
}
}
}
Here is an example of how it is being called:
Brooke, there is a small bug in your 'j' loop. You had saved the state of a variable (temp), however your logic in the j loop lost the state. This new logic preserves the state of the previous element in the list.
Try this:
for (int j = i - 1; j >= 0; j--) {
int t2 = maxList.get(j);
maxList.set(j, temp);
temp = t2;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
class arr{
//array sorting to find maximum value
public static void main(String[]args){
int[] array={1,6,4,5,2};
int n;
int i,j;
for( i=0;i<(array.length*2);i++){
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
}
System.out.println(array[array.length]);
}
}
>
Can anyone tell me why i am getting runtime error and this sorting method will work or not?
Dont reinvent the wheel.., you are able to use arrays, so then use the array help class too...
:-)
public static void main(String[] args) {
final int[] array = { 1, 6, 4, 5, 2 };
System.out.println("Array before sort " + Arrays.toString(array));
Arrays.sort(array);
System.out.println("Array before sort " + Arrays.toString(array));
}
you will likely have an indexOutOfbounds exception because your second loop:
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
J loops through teh array then you attempt to index the array at J + 1 which on the last element in the array would push it out of bounds thus throwing an outOfBoundsException
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
Since array.length = 5 and j < array.length, the value array[j+1] in the last round of the inner loop cause array out of bound exception.
The swap needs another variable to hold array[j] before changing it.
e.g:
int x;
for( j=0;j<array.length - 1;j++){
if(array[j]>array[j+1]){
x = array[j];
array[j]=array[j+1];
array[j+1]=x;
}
}
The bubble sort algorithm can be implemented as follows
public static void sort(int[] arr){
int len = arr.length;
int k = 0;
for(int j = 0 ; j < len-1; j++){
for(int i= 0+k; i < len-1; i += 2){
if(arr[i] <= arr[i+1])
continue;
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
k++;
if ( k % 2 == 0)
k = 0;
} }
The inner loop must alternately start at indexes 0 and 1 so as not to always swap the same pairs (k variable).
The others have already pointed out why you're getting an exception.
I was practicing on CodingBat when I came across this problem I couldn't quite get right. Given an array of positive integers, I must create an array of length "count" containing the first even numbers from the original array. The original array will contain at least "count" even numbers. My code is below, though I know that everything below the first if statement does not work and the "counter" variable is basically useless.
public int[] copyEvens(int[] nums, int count) {
int counter = 0;
int[] countArr = new int [count];
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
//what to put here?
}
}
return countArr;
}
any help would be much appreciated.
The following is incorrect:
if (i == count) {
This checks the position in the input array, rather than the position in the output array, against count.
public int[] copyEvens(int[] nums, int count) {
int counter = 0;
int[] countArr = new int [count];
for (int i = 0; i < nums.length && counter < count; i++)
if ((nums[i] % 2) == 0)
countArr[counter++] = nums[i];
return countArr;
}
School stuff... right?
I think you should be comparing the
counter... which starts at 0 .. so you need to add 1 as I am pretty sure count does not include 0 as an index.
Thus,
if((counter+1) ==count)
should replace the original.
I'm trying to create a list of 20 integers between 0 and 26 (so in the 1-25 range) that does not repeat as a part of an assignment. I thought I had it figured out, but the program keeps looping over and over without ever ending. Can anyone help me out?
import java.util.Random;
public class prog433a
{
public static void main(String args[])
{
Random r = new Random();
int[] list = new int[20];
for (int k = 0; k < list.length; k++)
{
boolean notADupe = false;
while (notADupe == false)
{
list[k] = r.nextInt(25) + 1;
for (int j = 0; j < list.length; j++)
{
if (list[j] == list [k] && j != k)
{
notADupe = true;
}
else
{
notADupe = false;
break;
}
}
System.out.println(list[k]);
}
}
}
}
EDIT: This is different from the other question because I am trying to figure out how to check for uniqueness using the methods that I am allowed to use in my assignment (essentially, the ones I'm already using in the code).
I think you've reversed the condition out there. Inside if, you should set notADup to false, rather than true. However, I would make the variable isDup instead, and change the while loop accordingly.
One more suggestion: instead of while (notADupe == false), you should just use while (!notADupe). Never compare boolean variables like that. It might surprise you at times.
So to solve your issue, just change your if-else block to:
if (list[j] == list [k] && j != k) {
notADupe = false;
break;
} else {
notADupe = true;
}
BTW, your solution is a bit complex. For every element, you are iterating over whole array to find duplicate. Rather I would suggest you to maintain a Set<Integer> storing the already seen numbers, and check in that every randomly generated number. If present, skip it and re-generate.
Pseudo code would look something like this:
arr = [] // Your list array, initialize to size 20
seen = [] // A Set
for i from 1 -> arr.length
num = rand.nextInt(25) + 1
while seen contains num
num = rand.nextInt(25) + 1
seen.add(num)
arr[i] = num