周赛141
- 复写零
public void duplicateZeros(int[] arr) {
for(int i = 0;i < arr.length - 1;i++){
if(arr[i] == 0){
for(int j = arr.length - 1;j > i;j--){
arr[j] = arr[j - 1];
}
arr[i + 1] = 0;
i++;
}
}
}
- 受标签影响的最大值
public int largestValsFromLabels(int[] values, int[] labels, int num_wanted, int use_limit) {
int len = values.length;
int[][] pair = new int[len][3];
int res = 0;
HashMap<Integer,Integer> limit = new HashMap<>();
for(int i = 0;i < len;i++){
pair[i][0] = values[i];
pair[i][1] = labels[i];
if(!limit.containsKey(labels[i])){
limit.put(labels[i],0);
}
}
Arrays.sort(pair, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o2[0] - o1[0];
}
});
int count = 0;
for(int i = 0;i < len;i++){
if(limit.get(pair[i][1]) < use_limit){
limit.put(pair[i][1],limit.get(pair[i][1])+1);
res += pair[i][0];
count++;
}
if(count >= num_wanted)
break;
}
return res;
}
- 二进制矩阵中的最短路径
class girdNode{
int x;
int y;
int step;
public girdNode(int x,int y,int step){
this.x = x;
this.y = y;
this.step = step;
}
}
public int shortestPathBinaryMatrix(int[][] grid) {
int n = grid.length;
if(grid[0][0] == 1 || grid[n-1][n-1] == 1 || n == 0)
return -1;
int[][] dir = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};
int[][] visited = new int[n][n];
visited[0][0] = 1;
LinkedList<girdNode> queue = new LinkedList<>();
girdNode node = new girdNode(0,0,1);
queue.add(node);
while (!queue.isEmpty()){
girdNode cur = queue.pop();
int val = cur.step;
if(cur.x == n - 1 && cur.y == n - 1) {
return cur.step;
}
for(int i = 0;i < 8;i++){
int x = cur.x + dir[i][0];
int y = cur.y + dir[i][1];
if(x >= 0 && y >= 0 && x < n && y < n && grid[x][y] == 0 && visited[x][y] != 1){
queue.add(new girdNode(x,y,val + 1));
visited[x][y] = 1;
}
}
}
return -1;
}
- 最短公共超序列
public String shortestCommonSupersequence(String str1, String str2) {
int l1 = str1.length(),l2 = str2.length();
int[][] LCS = new int[l1 + 1][l2 + 1];
for(int i = 0;i < l1;i++){
for(int j = 0;j < l2;j++){
if(str1.charAt(i) == str2.charAt(j)){
LCS[i+1][j+1] = LCS[i][j] + 1;
} else {
LCS[i+1][j+1] = Math.max(LCS[i][j+1],LCS[i+1][j]);
}
}
}
StringBuffer lcs = new StringBuffer();
int i = l1,j = l2,l = LCS[l1][l2];
while (l > 0){
if(str1.charAt(i-1) == str2.charAt(j-1)){
lcs.append(str1.charAt(i-1));
i--;
j--;
l--;
} else {
if(LCS[i-1][j] == l){
i--;
}else {
j--;
}
}
}
i = 0;
j = 0;
StringBuffer res = new StringBuffer();
for(char c:lcs.reverse().toString().toCharArray()){
while (i < l1 && str1.charAt(i) != c){
res.append(str1.charAt(i));
i++;
}
while (j < l2 && str2.charAt(j) != c){
res.append(str2.charAt(j));
j++;
}
res.append(c);
i++;
j++;
}
return res.toString() + str1.substring(i) + str2.substring(j);
}