Created
June 17, 2018 23:28
-
-
Save pinkmomo027/f0c9c584153e395cf9affa4d6f79deed to your computer and use it in GitHub Desktop.
count consecutive number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr = [-1, -1, 1, 1, 1, 1, 7, 11, 11]; | |
// [ -1, 2, 1, 4, 7, 1, 11, 2]; | |
class Stack { | |
constructor() { | |
this.values = []; | |
} | |
push(v) { | |
this.values.push(v); | |
} | |
pop() { | |
return this.values.pop(); | |
} | |
peek() { | |
return this.values[this.values.length - 1]; | |
} | |
isEmpty() { | |
return this.values.length == 0; | |
} | |
} | |
function countFrequency(arr) { | |
let stack = new Stack(); | |
let answer = [], count, currentElementInStack, element; | |
for (let i = 0; i <= arr.length; i++) { | |
element = arr[i]; | |
if ((stack.peek() != element) && !stack.isEmpty()) { | |
//start poping and clear the stack | |
count = 0; | |
currentElementInStack = stack.peek(); | |
while(!stack.isEmpty()) { | |
stack.pop(); | |
count++; | |
} | |
answer.push(currentElementInStack); | |
answer.push(count); | |
} | |
stack.push(element); | |
} | |
return answer; | |
} |
Author
pinkmomo027
commented
Jun 17, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment