tian
BAN USERimport java.util.ArrayList;
public class Matrix {
public static int[][] setZeroRowsCols(int[][] matrix){
int len = matrix.length;
ArrayList<Pair> locations = new ArrayList<Pair>();
for(int i=0; i<len; i++){
for(int j=0; j<matrix[i].length; j++){
if(matrix[i][j]==0){
locations.add(new Pair(i,j));
}
}
}
for(Pair pair : locations){
int iPos = pair.iPos;
int jPos = pair.jPos;
for(int i=0; i<len; i++){
matrix[i][jPos]=0;
}
for(int j=0; j<matrix[iPos].length; j++){
matrix[iPos][j]=0;
}
}
return matrix;
}
private static void printMatrix(int[][] matrix) {
int len = matrix.length;
for(int i=0; i<len; i++){
for(int j=0; j<matrix[i].length; j++){
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
static class Pair{
int iPos;
int jPos;
public Pair(int i, int j){
this.iPos = i;
this.jPos = j;
}
public Pair(){}
}
public static void main(String[] args){
int[][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,0,11},
{12,13,14,15}
};
System.out.println("Input:");
printMatrix(matrix);
matrix = setZeroRowsCols(matrix);
System.out.println("Output:");
printMatrix(matrix);
}
}
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class QueueStack<T> {
Queue<T> queue1 = new ConcurrentLinkedQueue<T>();
Queue<T> queue2 = new ConcurrentLinkedQueue<T>();
public void push(T elem){
queue1.offer(elem);
}
public T pop(){
if(!queue1.isEmpty()){
while(queue1.size()>1){
queue2.offer(queue1.poll());
}
return queue1.poll();
}else if(!queue2.isEmpty()){
while(queue2.size()>1){
queue1.offer(queue2.poll());
}
return queue2.poll();
}else{
return null;
}
}
public T peek(){
if(!queue1.isEmpty()){
while(queue1.size()>1){
queue2.offer(queue1.poll());
}
return queue1.peek();
}else if(!queue2.isEmpty()){
while(queue2.size()>1){
queue1.offer(queue2.poll());
}
T desiredelem = queue2.poll();
queue1.offer(desiredelem);
return desiredelem;
}else{
return null;
}
}
public static void main(String[] args){
QueueStack<Integer> testStack = new QueueStack<Integer>();
testStack.push(1);
testStack.push(2);
testStack.push(3);
System.out.println(testStack.pop());
System.out.println(testStack.pop());
System.out.println(testStack.pop());
}
}
- tian February 06, 2014
I like this idea.
- tian April 05, 2014