NC_18_ROTATEMATRIX-NC_19_maxsumofSubarray-NC_20_restoreIpAddresses
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/8/14 */ public class NC_18_ROTATEMATRIX { public int[][] rotateMatrix(int[][] mat, int n) { // write code here // 对角线 for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = temp; } } // 以竖轴翻转 for (int i = 0; i < n; i++) { for (int j = 0; j < n / 2; j++) { int temp = mat[i][j]; mat[i][j] = mat[i][n - 1 - j]; mat[i][n - 1 - j] = temp; } } return mat; } }
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/8/31 */ public class NC_19_maxsumofSubarray { public static int maxsumofSubarray(int[] arr) { // write code here //存放临时答案 int thisSum = 0; //存放最终答案,注意初始化的值 int ans = Integer.MIN_VALUE; int len = arr.length; for (int i = 0; i < len; i++) { //累加求和 thisSum += arr[i]; if (thisSum > ans) { ans = thisSum; } //贪心,负数必然会拉低序列和 if (thisSum < 0) { thisSum = 0; } } return ans; } public static int maxsumofSubarray2(int[] arr) { // write code here int sum = 0; int max = Integer.MIN_VALUE; for (int value : arr) { sum = sum + value; if (sum > max) { max = sum; } if (sum < 0) { sum = 0; } } return max; } public static void main(String[] args) { int[] arr = {1, 2, -99, 5, -5}; System.out.println(maxsumofSubarray2(arr)); } }
package org.example.interview.practice; import java.util.ArrayList; /** * @author xianzhe.ma * @date 2021/8/31 */ public class NC_20_restoreIpAddresses { /** * * @param s string字符串 * @return string字符串ArrayList */ public ArrayList<String> restoreIpAddresses (String s) { // write code here ArrayList<String> list=new ArrayList<>(); if(s.length()==0)return list; backTrack(s,0,3,list); return list; } //i:本次插入的起始位置 cnt:剩余可插入'.'的次数 public void backTrack(String s,int i,int cnt,ArrayList<String> list){ if(cnt==0){ String[] strs=s.split("\\."); //'.'要转义 if(strs.length<4)return ; //保证插入得到4个子串,不会出现多个'.'相连的情况 for(String str:strs){ if(str.length()>1&&str.charAt(0)=='0')return ; //排除有前导0的情况 if(Integer.parseInt(str)<0||Integer.parseInt(str)>255)return ; //排除不在范围的情况 } list.add(s); return ; } if(i>=s.length())return ; //没插完就结束的情况 int n=s.length(); backTrack(s.substring(0,i+1)+"."+s.substring(i+1,n),i+2,cnt-1,list); //插入到1个字符之后 if(i+2<n)backTrack(s.substring(0,i+2)+"."+s.substring(i+2,n),i+3,cnt-1,list); //插入到2个字符之后 if(i+3<n)backTrack(s.substring(0,i+3)+"."+s.substring(i+3,n),i+4,cnt-1,list); //插入到3个字符之后 } }