题目:
在4x4的棋盘上摆满了黑白棋子,黑白两色的位置和数目随机其中左上角坐标为(1,1),右下角坐标为(4,4),现在依次有一些翻转操作,要对一些给定支点坐标为中心的上下左右四个棋子的颜色进行翻转,请计算出翻转后的棋盘颜色。
给定两个数组A和f,分别为初始棋盘和翻转位置。其中翻转位置共有3个。请返回翻转后的棋盘。
测试样例:
[[0,0,1,1],[1,0,1,0],[0,1,1,0],[0,0,1,0]],[[2,2],[3,3],[4,4]]
返回:[[0,1,1,1],[0,0,1,0],[0,1,1,0],[0,0,1,0]]
public class chessBoard {
public static void main(String[] args) {
int arr[][] = {{0,0,1,1},{1,0,1,0},{0,1,1,0},{0,0,1,0}};
int[][] F={{2,2},{3,3},{4,4}};
int[][] result=new int[4][4];
result=flipChess(arr,F);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(result[i][j]);
}
System.out.println();
}
}
public static int[][] flipChess(int[][] A, int[][] f) {
// write code here
for(int i=0;i<f.length;i++){
int m=f[i][0]-1;
int n=f[i][1]-1;
if(m+1<A.length){
if(A[m+1][n]!=0){
A[m+1][n]=0;
}else{
A[m+1][n]=1;
}
}
if(n+1<A.length){
if(A[m][n+1]!=0){
A[m][n+1]=0;
}else{
A[m][n+1]=1;
}
}
if( n-1>=0){
if(A[m][n-1]!=0){
A[m][n-1]=0;
}else{
A[m][n-1]=1;
}
}
if(m-1>=0 ){
if(A[m-1][n]!=0){
A[m-1][n]=0;
}else{
A[m-1][n]=1;
}
}
}
return A;
}
}
精简算法
public class chessBoard {
public static void main(String[] args) {
int arr[][] = {{0,0,1,1},{1,0,1,0},{0,1,1,0},{0,0,1,0}};
int[][] F={{2,2},{3,3},{4,4}};
int[][] result=new int[4][4];
result=flipChess(arr,F);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(result[i][j]);
}
System.out.println();
}
}
public static int[][] flipChess(int[][] A, int[][] f) {
// write code here
for(int i=0;i<f.length;i++){
int m=f[i][0]-1;
int n=f[i][1]-1;
if(m+1<A.length){
A[m+1][n]=A[m+1][n]^1;
}
if(n+1<A.length){
A[m][n+1]=A[m][n+1]^1;
}
if( n-1>=0){
A[m][n-1]=A[m][n-1]^1;
}
if(m-1>=0){
A[m-1][n]=A[m-1][n]^1;
}
}
return A;
}
}
题目描述
世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么?示例1输入
1999 2299输出
7public class binaryDiffNum { public static void main(String[] args) { // TODO Auto-generated method stub int a=16807; int b=282475249; int c=countBitDiff(a,b); System.out.println(c); } public static int countBitDiff(int m, int n) { int count=0; int temp=n^m; while(temp!=0){ ++count; temp&=(temp-1); } return count; } }
风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 输入数值范围:2<=n<=100,0<=prices[i]<=100最优算法:?、?????示例1输入
3,8,5,1,7,8输出
12别人的代码:if(prices == null || prices.length < 2){ return 0; } int firstBuy = Integer.MIN_VALUE; int firstSell = 0; int secondBuy = Integer.MIN_VALUE; int secondSell = 0; for(int num : prices){ firstBuy = Math.max(firstBuy,-num); firstSell = Math.max(firstSell, firstBuy + num); secondBuy = Math.max(secondBuy, firstSell - num); secondSell = Math.max(secondSell, secondBuy + num); } return secondSell; }