7,Dynamic Programming

1,Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

Analyse:

public class Solution {
public int uniquePaths(int m, int n)
{
int[][] dp = new int[m][n];
for (int i = 0; i < n; i++) {
dp[0][i] = 1;
}
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
}

滚动指针来优化空间复杂度:

public class Solution {
public int uniquePaths(int m, int n)
{
int[][] dp = new int[2][n];
for (int i = 0; i < n; i++) {
dp[0][i] = 1;
}
dp[0][0] = 1;
for (int i = 1; i < m; i++) {
dp[i % 2][0] = 1;
for (int j = 1; j < n; j++) {
dp[i % 2][j] = dp[(i - 1) % 2][j] + dp[i % 2][j - 1];
}
}
return dp[(m - 1) % 2][n - 1];
}
}

1--follow up :有障碍物。

public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0) {
return 0;
}
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
// initialize
for (int i = 0; i < m; i++) {
if (obstacleGrid[i][0] != 1) {
dp[i][0] = 1;
} else {
break;
}
}
for (int j = 0; j < n; j++) {
if (obstacleGrid[0][j] != 1) {
dp[0][j] = 1;
} else {
break;
}
}
// calculate
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] != 1) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
}

滚动数组优化:

public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0) {
return 0;
}
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] dp = new int[2][n];
for (int j = 0; j < n; j++) {
if (obstacleGrid[0][j] != 1) {
dp[0][j] = 1;
} else {
break;
}
}
// calculate
for (int i = 1; i < m; i++) {
if (dp[(i - 1) % 2][0] != 0 && obstacleGrid[i][0] != 1) {
dp[i % 2][0] = 1;
} else {
dp[i % 2][0] = 0;
}
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] != 1) {
dp[i % 2][j] = dp[(i - 1) % 2][j] + dp[i % 2][j - 1];
} else {
dp[i % 2][j] = 0;
}
}
}
return dp[(m - 1) % 2][n - 1];
}
}

2,Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Analyse:

public class Solution {
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[2][n];
dp[0][0] = grid[0][0];
// for (int i = 1; i < m; i++) {
// dp[i][0] = dp[i - 1][0] + grid[i][0];
// }
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
for (int i = 1; i < m; i++) {
dp[i % 2][0] = dp[(i - 1) % 2][0] + grid[i][0];
for (int j = 1; j < n; j++) {
dp[i % 2][j] = Math.min(dp[(i - 1) % 2][j], dp[i % 2][j - 1]) + grid[i][j];
}
}
return dp[(m - 1) % 2][n - 1];
}
}

3,climb stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Subscribe to see which companies asked this question

Analyse:

public class Solution {
public int climbStairs(int n) {
if (n <= 0) {
return 0;
}
if (n <= 2) {
return n;
}
int[] dp = new int[2];
dp[0] = 1;
dp[1] = 2;
for (int i = 2; i < n; i++) {
dp[i % 2] = dp[(i - 1) % 2] + dp[(i - 2) % 2];
}
return dp[(n - 1) % 2];
}
}

4,maximum subarray

public class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] dp = new int[2];
int max = nums[0];
dp[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i % 2] = Math.max(dp[(i - 1) % 2] + nums[i], nums[i]);
max = Math.max(max, dp[i % 2]);
}
return max;
}
}

5,triangle

public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
}
int size = triangle.size();
for (int i = size - 2; i >= 0; i--) {
// find the min
for (int j = 0; j <= i; j++) {
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
}
}
return triangle.get(0).get(0);
}
}

6,best time to buy and sell stock

public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
}

7,

6,Recursion

1,climb building (print all the possible ways)

Analyse:

public class Solution {
public static void main(String[] args) {
climb(, "");
}
public static void climb(int n, String preWay) {
if (n == ) {
System.out.println(preWay + "");
return;
}
if (n == ) {
System.out.println(preWay + "");
System.out.println(preWay + " 1 1");
return;
}
String preWay1 = preWay + "";
climb(n - , preWay1);
String preWay2 = preWay + "";
climb(n - , preWay2);
}
}

2,Hanoi

Analyse : Move the first (n - 1) disk from A to B; then move the nth disk from A to C; move the other (n - 1) disk from b to c.

(1) how many steps we need to move all n disks from A to C.

import java.io.*;
class test
{
public static void main (String[] args) {
System.out.println(hanoiSteps(3));
}
public static int hanoiSteps(int n) {
if (n == 1) {
return 1;
}
return hanoiSteps(n - 1) + 1 + hanoiSteps(n - 1);
} }

(2) Print all the steps that is needed to move all n disks from A to C.

import java.io.*;
class test
{
public static void hanoi(int n, char source, char spare, char target) {
if (n == 1) {
System.out.println("Move " + source + " to " + target);
return;
}
hanoi(n - 1, source, target, spare);
System.out.println("Move " + source + " to " + target);
hanoi(n - 1, spare, source, target);
} }

(3) 0-1 knapsack

Given a knapsack which can hold s pounds of items, and a set of items with weight w1, w2, ... wn. Return whether we can pick specific items so that their total weight s. 

Analyse: pick it: (s - w[i], w - w[i]), or not pick it : (s, w - w[i]);

import java.io.*;
class test
{
public static void main(String[] args) {
int[] weights = {14, 8, 7, 5, 3};
System.out.println(knapsack(20, weights, 0));
}
public static boolean knapsack(int s, int[] weights, int index) {
if (s == 0) {
return true;
}
if (s < 0 || index >= weights.length) {
return false;
}
return knapsack(s - weights[index], weights, index + 1) || knapsack(s, weights, index + 1);
} }

(4)0-1 knapsack

0-1 Knapsack II
Given a knapsack which can hold s pounds of items, and a set of items with
weight w1, w2, ... wn. Try to put items into the pack as many as possible, return
the largest weight we can get in the knapsack.

Analyse : pick it weights[index] + knapsack2, index + 1; not pick it : knapsack2,  index + 1;

public class Solution {
public int getMax(int s, int[] weights) {
return knapsack2(s, weights, 0);
}
public static int knapsack2(int s, int[] weights, int index) {
if (s == 0 || index == weights.length) {
return 0;
}
if (weights[index] > s) {
return knapsack2(s, weights, index + 1);
}
return Math.max(knapsack2(s, weights, index + 1), weights[index] + knapsack2(s - weights[index], weights, index + 1));
}
}

(5) knapsack III

Knapsack III
Given a set of candidate numbers (C) and a target number (T), find all unique
combinations in C where the candidate numbers sums to T.
All candidate numbers are unique.
The same repeated number may be chosen from C unlimited number of times.

Analyse :

import java.util.ArrayList;
import java.util.Arrays; public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> cur = new ArrayList<Integer>();
combine(candidates, 0, target, results, cur);
return results;
}
public void combine(int[] candidates, int index, int target,
ArrayList<ArrayList<Integer>> results,
ArrayList<Integer> cur) {
if (target < 0) {
return;
}
if (target == 0) {
results.add(new ArrayList<Integer>(cur));
return;
}
for (int i = index; i < candidates.length; i++) {
cur.add(candidates[i]);
combine(candidates, i, target-candidates[i], results, cur);
cur.remove(cur.size()-1);
}
return;
}
}

(6) knapsack III-2

Given a collection of candidate numbers (C) and a target number (T), find all
unique combinations in C where the candidate numbers sums to T.
Candidate numbers may contain duplicate.
Each number in C may only be used once in the combination.
import java.util.ArrayList;
import java.util.Arrays; public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> cur = new ArrayList<Integer>();
combine(candidates, 0, target, results, cur);
return results;
}
public void combine(int[] candidates, int index, int target,
ArrayList<ArrayList<Integer>> results,
ArrayList<Integer> cur) {
if (target < 0) {
return;
}
if (target == 0) {
results.add(new ArrayList<Integer>(cur));
return;
}
for (int i = index; i < candidates.length; i++) {
cur.add(candidates[i]);
combine(candidates, i + 1, target-candidates[i], results, cur);
cur.remove(cur.size()-1);
while (i < candidates.length - 1 && candidates[i] == candidates[i + 1]) {
i++;
}
}
return;
}
}

(7) maze

Maze
Given a maze and a start point and a target point, return whether the target can
be reached.
Example Input:
Start Point: (0, 0); Target Point (5, 5);
Maze: char[][] = {
{'.', 'X', '.', '.', '.', 'X'},
{'.', '.', '.', 'X', '.', 'X'},
{'X', 'X', '.', 'X', '.', '.'},
{'.', 'X', 'X', 'X', '.', 'X'},
{'.', '.', '.', '.', '.', 'X'},
{'.', '.', '.', '.', '.', '.'}
}
Example Output: True

Analyse:bfs

1,return whether the target can be reached

public class Solution {
public static void main(String[] args) {
char[][] maze= {
{'.', 'X', '.', '.', '.', 'X'},
{'.', '.', '.', 'X', '.', 'X'},
{'X', 'X', '.', 'X', '.', '.'},
{'.', 'X', 'X', 'X', '.', 'X'},
{'.', '.', '.', '.', '.', 'X'},
{'.', '.', '.', '.', '.', '.'}
};
System.out.println(solveMaze(maze, 0, 0, 5, 5));
}
public static boolean solveMaze(char[][] maze, int startX, int startY, int targetX, int targetY) {
if (startX == targetX && startY == targetY) {
return true;
}
maze[startX][startY] = 'X';
int[] dx = {1, 0, -1, 0};
int[] dy = {0, 1, 0, -1};
for (int i = 0; i < 4; i++) {
int newX = startX + dx[i];
int newY = startY + dy[i];
if (newX < 0 || newX >= maze.length || newY < 0 || newY >= maze[0].length || maze[newX][newY] == 'X') {
continue;
}
if (solveMaze(maze, newX, newY, targetX, targetY)){
return true;
}
}
return false;
}
}

2,print out the path to reach the target.

import java.util.ArrayList;
import java.util.Arrays; public class Solution {
public static void main(String[] args) {
ArrayList<Character> list = new ArrayList();
char[][] maze= {
{'.', 'X', '.', '.', '.', 'X'},
{'.', '.', '.', 'X', '.', 'X'},
{'X', 'X', '.', 'X', '.', '.'},
{'.', 'X', 'X', 'X', '.', 'X'},
{'.', '.', '.', '.', '.', 'X'},
{'.', '.', '.', '.', '.', '.'}
};
System.out.println(solveMaze(maze, 0, 0, 5, 5, list));
System.out.println(list);
}
public static boolean solveMaze(char[][] maze, int startX, int startY, int targetX, int targetY, ArrayList<Character> path) {
if (startX == targetX && startY == targetY) {
return true;
}
maze[startX][startY] = 'X';
int[] dx = {1, 0, -1, 0};
int[] dy = {0, 1, 0, -1};
char[] direction = {'R', 'U', 'L', 'D'};
for (int i = 0; i < 4; i++) {
int newX = startX + dx[i];
int newY = startY + dy[i];
path.add(direction[i]);
if (newX < 0 || newX >= maze.length || newY < 0 || newY >= maze[0].length || maze[newX][newY] == 'X') {
continue;
}
if (solveMaze(maze, newX, newY, targetX, targetY, path)){
return true;
}
path.remove(path.size() - 1);
}
return false;
}
}

(8) generate parentheses

22. Generate Parentheses  QuestionEditorial Solution  My Submissions
Total Accepted: 96789
Total Submissions: 251907
Difficulty: Medium
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

Analyse: use left and right to remeber the leaved numbers of left parenthesis and right parenthesis. left == 0 && right == 0, put the string into list.

public class Solution {
public List<String> generateParenthesis(int n) {
List<String> results = new ArrayList();
generateParenthesis(results, "", n, n);
return results;
}
public static void generateParenthesis(List<String> results, String prefix, int left, int right) {
if (left == 0 && right == 0) {
results.add(prefix);
return;
}
if (left > 0) {
generateParenthesis(results, prefix + "(", left - 1, right);
}
if (left < right) {
generateParenthesis(results, prefix + ")", left, right - 1);
}
}
}

(9) permutation

46. Permutations  QuestionEditorial Solution  My Submissions
Total Accepted: 109331
Total Submissions: 294780
Difficulty: Medium
Given a collection of distinct numbers, return all possible permutations. For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

Analyse:

public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> results = new ArrayList();
List<Integer> listNow = new ArrayList();
results.add(listNow);
if (nums == null || nums.length == 0) {
return results;
}
for (int i = 0; i < nums.length; ++i) {
List<List<Integer>> temp = new ArrayList();
for (List<Integer> list : results) {
int size = list.size();
for (int j = 0; j <= size; ++j) {
List<Integer> cur = new ArrayList(list);
cur.add(j, nums[i]);
temp.add(cur);
}
}
results = new ArrayList(temp);
}
return results;
}
}

(10) permutation II

47. Permutations II  QuestionEditorial Solution  My Submissions
Total Accepted: 78186
Total Submissions: 271215
Difficulty: Medium
Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

Analyse: contains

public class Solution {
public static List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> results = new ArrayList();
List<Integer> listNow = new ArrayList();
results.add(listNow);
if (nums == null || nums.length == 0) {
return results;
}
for (int i = 0; i < nums.length; ++i) {
List<List<Integer>> temp = new ArrayList();
for (List<Integer> list : results) {
int size = list.size();
for (int j = 0; j <= size; ++j) {
List<Integer> cur = new ArrayList(list);
cur.add(j, nums[i]);
if (!temp.contains(cur)) {
temp.add(cur);
} }
}
results = new ArrayList(temp);
}
return results;
}
}

(11)subsets

78. Subsets  QuestionEditorial Solution  My Submissions
Total Accepted: 104901
Total Submissions: 320125
Difficulty: Medium
Given a set of distinct integers, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example,
If nums = [1,2,3], a solution is: [
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

Analyse:

public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> results = new ArrayList();
List<Integer> list = new ArrayList();
results.add(list);
if (nums == null || nums.length == 0) {
return results;
}
for (int i = 0; i < nums.length; ++i) {
List<List<Integer>> temp = new ArrayList(results);
for (List<Integer> now : results) {
List<Integer> listTemp= new ArrayList(now);
listTemp.add(nums[i]);
temp.add(listTemp);
}
results = new ArrayList(temp);
}
return results;
}
}

(12)find all the largest weight's  combination

Given a knapsack which can hold s pounds of items, and a set of items with
weight w1, w2, ... wn. Try to put items into the pack as many as possible, print out
all the items that can get the largest weight. Each item can only get picked once.

Analyse: first, find the largest weights, then find the combination.

import java.util.ArrayList;
import java.util.Arrays; public class Solution {
public ArrayList<ArrayList<Integer>> knapsackPrint(int s, int[] weights) {
// get the largest weight
int max = getMax(s, weights);
ArrayList<ArrayList<Integer>> results = new ArrayList();
results = combinationSum(weights, max);
System.out.println(results);
return results;
}
public static int getMax(int s, int[] weights) {
return knapsackMax(s, weights, 0);
}
public static int knapsackMax(int s, int[] weights, int index) {
if (s == 0 || index == weights.length) {
return 0;
}
if (weights[index] > s) {
return knapsackMax(s, weights, index + 1);
}
return Math.max(knapsackMax(s, weights, index + 1), weights[index] + knapsackMax(s - weights[index], weights, index + 1));
}
public static ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> cur = new ArrayList<Integer>();
combine(candidates, 0, target, results, cur);
return results;
}
public static void combine(int[] candidates, int index, int target,
ArrayList<ArrayList<Integer>> results,
ArrayList<Integer> cur) {
if (target < 0) {
return;
}
if (target == 0) {
results.add(new ArrayList<Integer>(cur));
return;
}
for (int i = index; i < candidates.length; i++) {
cur.add(candidates[i]);
combine(candidates, i + 1, target-candidates[i], results, cur);
cur.remove(cur.size()-1);
while (i < candidates.length - 1 && candidates[i] == candidates[i + 1]) {
i++;
}
}
return;
} }

5,Stack & Queue

(1)implement stack

class Stack<T> {
private int top;
int capacity;
T[] stack;
public Stack(int inCapacity) {
capacity = inCapacity;
stack = (T[]) new Object[capacity];
top = -1;
}
public int size() {
return top + 1;
}
public void push(T value) {
if (top + 1 == capacity) {
throw new IllegalStateException("Stack is full");
} else {
stack[++top] = value;
}
}
public T peek() {
if (top == -1) {
throw new IllegalStateException("Stack is empty");
} else {
return stack[top];
}
}
public T pop() {
if (top == -1) {
throw new IllegalStateException("Stack is empty");
} else {
return stack[top--];
}
}
}

(2) implement queue use array

class Queue<T> {
private int front;
private int rear;
int capacity;
int size;
T[] queue;
public Queue(int inCapacity) {
capacity = inCapacity;
queue = (T[]) new Object[capacity];
front = 0;
rear = 0;
size = 0;
}
public int size() {
return size;
}
public void add(T value) {
if (size == capacity) {
throw new IllegalStateException("Queue is full");
} else {
queue[rear] = value;
rear = (rear + 1) % capacity;
size++;
}
}
public T remove() {
T value = null;
if (size == 0) {
throw new IllegalStateException("Queue is empty, can't remove");
} else {
value = queue[front];
front = (front + 1) % capacity;
size--;
}
return value;
}
}

(3)min stack

155. Min Stack My Submissions QuestionEditorial Solution
Total Accepted: 77918 Total Submissions: 337784 Difficulty: Easy
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.

Analyse : two stack

public class MinStack {
Stack<Integer> stack;
Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack();
minStack = new Stack();
} public void push(int x) {
stack.push(x);
if (minStack.isEmpty()) {
minStack.push(x);
} else {
if (x < minStack.peek()) {
minStack.push(x);
} else {
minStack.push(minStack.peek());
}
}
} public void pop() {
stack.pop();
minStack.pop();
} public int top() {
return stack.peek();
} public int getMin() {
return minStack.peek();
}
} /**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/

(4)max stack

public class MaxStack {
Stack<Integer> stack;
Stack<Integer> maxStack;
/** initialize your data structure here. */
public MaxStack() {
stack = new Stack();
maxStack = new Stack();
} public void push(int x) {
stack.push(x);
if (maxStack.isEmpty()) {
maxStack.push(x);
} else {
if (x > maxStack.peek()) {
maxStack.push(x);
} else {
maxStack.push(maxStack.peek());
}
}
} public void pop() {
stack.pop();
maxStack.pop();
} public int top() {
return stack.peek();
} public int getMax() {
return maxStack.peek();
}
}

(5)valid parentheses

20. Valid Parentheses My Submissions QuestionEditorial Solution
Total Accepted: 115251 Total Submissions: 384811 Difficulty: Easy
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Analyse : two error

public class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
Stack<Character> stack = new Stack();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) { // Error 1
return false;
}
char pre = stack.pop();
if (c == ')') {
if ( pre != '(') {
return false;
}
} else if (c == ']') {
if (pre != '[') {
return false;
}
} else {
if (pre != '{') {
return false;
}
}
}
}
if (stack.isEmpty()) { //Error 2
return true;
}
return false;
}
}

(6)implement queue usint stacks

232. Implement Queue using Stacks My Submissions QuestionEditorial Solution
Total Accepted: 47988 Total Submissions: 140316 Difficulty: Easy
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Analyse: two stack

class MyQueue {
// Push element x to the back of queue.
Stack<Integer> stack1 = new Stack();
Stack<Integer> stack2 = new Stack();
public void push(int x) {
stack1.push(x);
} // Removes the element from in front of queue.
public void pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.add(stack1.pop());
}
}
stack2.pop();
} // Get the front element.
public int peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.add(stack1.pop());
}
}
// Error: stack2.pop();
return stack2.peek();
} // Return whether the queue is empty.
public boolean empty() {
if (stack1.isEmpty() && stack2.isEmpty()) {
return true;
}
return false;
}
}

(6) implement stack use queues

225. Implement Stack using Queues My Submissions QuestionEditorial Solution
Total Accepted: 43270 Total Submissions: 140856 Difficulty: Easy
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Analyse : use two queues, keep one of them is empty. push x into the queues which is empty, and them push all

elements of another queue into it. when you want to pop , you just poll the queue's top element which is not empty.

class MyStack {
Queue<Integer> queue1 = new LinkedList();
Queue<Integer> queue2 = new LinkedList(); // Push element x onto stack.
public void push(int x) {
if (queue1.isEmpty()) {
queue1.add(x);
while (!queue2.isEmpty()) {
queue1.add(queue2.poll());
}
} else {
queue2.add(x);
while (!queue1.isEmpty()) {
queue2.add(queue1.poll());
}
}
} // Removes the element on top of the stack.
public void pop() {
if (!queue1.isEmpty()) {
queue1.poll();
} else {
queue2.poll();
}
} // Get the top element.
public int top() {
if (!queue1.isEmpty()) {
return queue1.peek();
} else {
return queue2.peek();
}
} // Return whether the stack is empty.
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}

(7) cows facing right

=
= - Cows facing right -->
= = =
= - = = =
= = = = = =
1 2 3 4 5 6
Copyright ©

Preparing for the interview of FLAG and USDA的更多相关文章

  1. UNIX command Questions Answers asked in Interview

    UNIX or Linux operating system has become default Server operating system and for whichever programm ...

  2. Cracking Digital VLSI Verification Interview 第三章

    目录 Programming Basics Basic Programming Concepts Object Oriented Programming Concepts UNIX/Linux Pro ...

  3. JVM故障处理工具,使用总结

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 用都用不到怎么学? 没有场景.没有诉求,怎么学习这些似乎用不上知识点. 其实最好的方 ...

  4. Python interview preparing

    Collection & Recommended: 1. CN - 论坛中看到. - EN 英文原文真的真的很好好好T_T,看得让人感动T_T 总结个人感兴趣的问题(以下部分参照上面): 1. ...

  5. Core Java Interview Question Answer

    This is a new series of sharing core Java interview question and answer on Finance domain and mostly ...

  6. Java Interview Reference Guide--reference

    Part 1 http://techmytalk.com/2014/01/24/java-interview-reference-guide-part-1/ Posted on January 24, ...

  7. interview material

    Articles Recommended: Steve Yegge – Get That Job at Google [web] Carlos Bueno – Get That Job at Face ...

  8. Inhouse interview(websense)

    1.Tell me about yourself? My name is xxx,i 'm from xxx. now , I am a postgratuation and my major sub ...

  9. JULIA BOORSTIN — Interview a Broadcaster!

    JULIA BOORSTIN — Interview a Broadcaster! Share Tweet Share Tagged With: Interview a Broadcaster Stu ...

随机推荐

  1. 关于mybatis中多参数传值

    如果前台单独传递多个参数,并且未进行封装,在mybatis的sql映射文件中需要以下标的形式表示传递的参数,从0开始 即:where name=#{0} and password =#{1}:0表示第 ...

  2. Atcoder Beginner Contest151E(排列组合)

    排列组合 #define HAVE_STRUCT_TIMESPEC #include<bits/stdc++.h> using namespace std; ]; ; ]; long lo ...

  3. UIAutomation反编译调试一句话体验

    ILSpy比dotpeek好使 ILSpy生成的pdb调试起来基本没发现问题,最多只是代码步骤位置和实际位置差了一行而已,不影响判断. dotpeek反编译出来的代码能看,但调试是基本没办法定位的,位 ...

  4. js判断是横屏还是竖屏

    1通过在html中分别引用横屏和竖屏的样式: <link rel="stylesheet" media="all and (orientation:portrait ...

  5. echart 重新加载

    myechart2.clear(); myechart2.setOption(options[1]);

  6. php redis 集群扩展类文件

    <?php /** * redis集群驱动 */ namespace Common\Api; class RedisCluster{ protected $servers=array( '192 ...

  7. Tensorflow机器学习入门——读取数据

    TensorFlow 中可以通过三种方式读取数据: 一.通过feed_dict传递数据: input1 = tf.placeholder(tf.float32) input2 = tf.placeho ...

  8. 匹配 $gdinfo 中的数字

    <?php /* //下载 $filename = 'av.zip'; // 设置类型:可以省略 // header("content-type:image/jpeg"); ...

  9. history路由

    class HistoryRouter{ constructor(){ //用于存储不同path值对应的回调函数 this.routers = {}; this.listenPopState(); t ...

  10. SQL 函数 排序 等基础操作 DDL DML DQL 用法和<> <=>等

    sql基础汇总 --根据函数别名排序 --排序规则,默认是升序 sleect LENGTH(NAME) nameLength from user ORDER BY nameLength DESC -- ...