代码实现:
import java.util.ArrayList;
public class 螺旋矩阵 {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(matrix.length==0) return res;
int top =0;
//行数 最底行
int bottom = matrix.length-1;
int left =0;
//列数 最右列
int right = matrix[0].length-1;
while(true){
//顶层 从左到右
for(int i=left;i<=right;i++) res.add(matrix[top][i]);
top++;
//截至条件
if(left>right||top>bottom) break;
//右面 从上到下
for(int i = top;i<=bottom;i++) res.add(matrix[i][right]);
right--;
if(left>right||top>bottom) break;
//底层 从右往左
for(int i=right;i>=left;i--) res.add(matrix[bottom][i]);
bottom--;
if(left>right||top>bottom) break;
//左面 从下往上
for(int i=bottom;i>=top;i--) res.add(matrix[i][left]);
left++;
if(left>right||top>bottom) break;
}
return res;
}
}
2、进制转换
代码实现:
public class 进制转换 {
/**
* 进制转换
* @param M int整型 给定整数
* @param N int整型 转换到的进制
* @return string字符串
*/
public static String solve(int M, int N) {
// write code here
boolean nagative = false;
//负数处理
if(M<0){
nagative = true;
M = -M;
}
StringBuilder sb = new StringBuilder();
while (M>0){
int k = M%N;
//大于10进制的处理
if(k>=10){
sb.append((char)(k-10+'A'));
}else{
sb.append(k);
}
M = M/N;
}
//负数添加“-”
if(nagative){
sb.append("-");
}
//字符反转
return sb.reverse().toString();
}
public static void main(String[] args) {
int M = 125;
int N = 16;
System.out.println(solve(M,N));
}
}
3、买股票的最好时机
代码实现:
import java.util.Arrays;
public class 卖股票的好时机 {
/* *//**
*
* @param prices int整型一维数组
* @return int整型
*//*
public static int maxProfit(int[] prices) {
// write code here
if(null == prices || prices.length == 0) {
return 0;
}
Arrays.sort(prices);
return prices[prices.length-1]-prices[0];
}
public static void main(String[] args) {
int[] a ={1,2};
System.out.println(maxProfit(a));
}*/
public static int maxProfit(int[] prices) {
// write code here
if(prices==null||prices.length<2) return 0;
int profit =0,buy = prices[0];
for(int i=1;i<prices.length;i++){
buy = Math.min(buy,prices[i]);
profit = Math.max(profit,prices[i]-buy);
}
return profit;
}
public static void main(String[] args) {
int[] a ={1,4,2};
System.out.println(maxProfit(a));
}
}
4、缺失的数字
//方法一
import java.util.*;
public class Solution {
/**
* 找缺失数字
* @param a int整型一维数组 给定的数字串
* @return int整型
*/
public int solve (int[] a) {
// write code here
for(int i=0;i<a.length;i++){
if(i!=a[i])
return i;
}
return 0;
}
}
//方法二
import java.util.*;
public class Solution {
/**
* 找缺失数字
* @param a int整型一维数组 给定的数字串
* @return int整型
*/
public int solve (int[] a) {
// write code here
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(a[j]-a[j-1]!=1)
return j;
}
}
return 0;
}
}
//方法三
import java.util.*;
public class Solution {
/**
* 找缺失数字
* @param a int整型一维数组 给定的数字串
* @return int整型
*/
public int solve (int[] a) {
// write code here
int sum =0;
if(a!=null){
int n = a.length;
sum = (n*(n+1))/2;
for(int i=0;i<n;i++){
sum = sum-a[i];
}
}
return sum;
}
}