Preparing for the interview of FLAG and USDA
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的更多相关文章
- UNIX command Questions Answers asked in Interview
UNIX or Linux operating system has become default Server operating system and for whichever programm ...
- Cracking Digital VLSI Verification Interview 第三章
目录 Programming Basics Basic Programming Concepts Object Oriented Programming Concepts UNIX/Linux Pro ...
- JVM故障处理工具,使用总结
作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 用都用不到怎么学? 没有场景.没有诉求,怎么学习这些似乎用不上知识点. 其实最好的方 ...
- Python interview preparing
Collection & Recommended: 1. CN - 论坛中看到. - EN 英文原文真的真的很好好好T_T,看得让人感动T_T 总结个人感兴趣的问题(以下部分参照上面): 1. ...
- Core Java Interview Question Answer
This is a new series of sharing core Java interview question and answer on Finance domain and mostly ...
- Java Interview Reference Guide--reference
Part 1 http://techmytalk.com/2014/01/24/java-interview-reference-guide-part-1/ Posted on January 24, ...
- interview material
Articles Recommended: Steve Yegge – Get That Job at Google [web] Carlos Bueno – Get That Job at Face ...
- 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 ...
- JULIA BOORSTIN — Interview a Broadcaster!
JULIA BOORSTIN — Interview a Broadcaster! Share Tweet Share Tagged With: Interview a Broadcaster Stu ...
随机推荐
- Eclipse配置C++11环境详细介绍
转:https://blog.csdn.net/wgxh05/article/details/54021049 本文记录Eclipse配置C++11开发所有作者遇到的情况,包括跨工程文件编译,内联文件 ...
- Linux实现树莓派3B的国密SM9算法交叉编译——(二)miracl库的测试与静态库的生成
先参考这篇文章 Linux实现树莓派3B的国密SM9算法交叉编译——(一)环境部署.简单测试与eclipse工程项目测试 部署好环境,并简单测试交叉编译环境是否安装成功,最后实现在Eclipse上进行 ...
- IPSec无法建立?注意第一阶段hash sha !
该篇注意记录一下,有些情况下,我们配置了IPSec ,但是就是无法建立,发现连第一阶段都无法建立起来. 1.检查配置无问题 2.开启debug crypto isakmp发现有IKE的重传 3.sho ...
- Docker - 创建第一个 docker 实例
1. 概述 安装完准备开始使用 2. 环境 os centos 7 docker docker - ce 19.03 3. 步骤 启动docker > systemctl start docke ...
- mysql 隔离性与隔离级别
提到事务,你肯定不陌生,和数据库打交道的时候,我们总是会用到事务.最经典的例子就是转账,你要给朋友小王转 100 块钱,而此时你的银行卡只有 100 块钱. 转账过程具体到程序里会有一系列的操作,比如 ...
- JS-常用方法合集
部分方法使用jQuery!!!//tab切换 /* * 参数tablist为触发事件id * 参数tabmain为执行切换id * 参数ev为触发事件的动作 */ function tab(tabli ...
- Vue - 实现双击显示编辑框;自动聚焦点击的显示框;点击编辑框外的地方,隐藏编辑框
实现这三个功能的踩坑记录. 1. 需求 在Vue中,有一个input, 双击时编辑文本,点击该input节点外的其他地方,则取消编辑. 那么这里有三个要实现的地方 第一是双击显示编辑框. 第二是自动聚 ...
- Ubuntu16 nginx 配置 Let's Encrypt 免费ssl
每篇一句 Some of us get dipped in flat, some in satin, some in gloss. But every once in a while you find ...
- Educational Codeforces Round 75 (Rated for Div. 2)D(二分)
#define HAVE_STRUCT_TIMESPEC#include<bits/stdc++.h>using namespace std;pair<int,int>a[20 ...
- Java数字和字符的对照关系表
/* 数字和字符的对照关系表(编码表): ASCII码表:American Standard Code for Information Interchange,美国信息交换标准代码. Unicode码 ...