Skip to content

add array solution for 1381 #127

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/main/java/com/fishercoder/solutions/_1381.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,43 @@ public void increment(int k, int val) {
}
}
}

/**
* Implementation of Stack using Array
*/
public static class Solution2{
public static class CustomStack {
private int top;
private int maxSize;
private int stack[];
public CustomStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
}

public void push(int x) {
if(top == maxSize) return;
stack[top] = x;
top++;
}

public int pop() {
if(top == 0)
return -1;
int popValue = stack[top-1];
stack[top-1] = 0;
top--;
return popValue;
}

public void increment(int k, int val) {
if(top == 0 || k == 0) return;
for(int i = 0; i<k; i++){
if(i == top)
break;
stack[i] += val;
}
}
}
}
}
16 changes: 16 additions & 0 deletions src/test/java/com/fishercoder/_1381Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

public class _1381Test {
private static _1381.Solution1.CustomStack customStack;
private static _1381.Solution2.CustomStack customStack2;

@Test
public void test1() {
Expand All @@ -24,5 +25,20 @@ public void test1() {
assertEquals(201, customStack.pop());
assertEquals(-1, customStack.pop());
}
@Test
public void test2() {
customStack2 = new _1381.Solution2.CustomStack(3);
customStack2.push(-1);
customStack2.push(20);
assertEquals(20, customStack2.pop());
customStack2.push(30);
customStack2.push(40);
customStack2.push(50);
customStack2.increment(5, 100);
assertEquals(140, customStack2.pop());
assertEquals(130, customStack2.pop());
assertEquals(99, customStack2.pop());

}

}