20200220
题目 :零矩阵,编写一种算法,若M*N矩阵中某个元素为0,则将其所在行与列清零。
思路 :通过遍历矩阵,找到0的索引下标,多所在行,列清零。
code
public void setZeros(int[][] matrix){
HashSet<Integer> row_set = new HashSet<>(), col_set = new HashSet<>();
int row = matrix.length, col = matrix[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(matrix[i][j] == 0){
row_set.add(i);
col_set.add(j);
}
}
}
for(int row_idx : row_set){
Arrays.fill(matrix[row_idx],0);
}
for(int col_idx : col_set){
for(int i = 0;i < row;i++){
matrix[i][col_idx]=0;
}
}
}
题目 :字符串反转。给定两个字符串s1
和s2
,请编写代码检查s2
是否为s1
旋转而成(比如,waterbottle
是erbottlewat
旋转后的字符串)。
示例1:
输入:s1 = "waterbottle", s2 = "erbottlewat"
输出:True
思路 :对给定的两个字符进行排序,之后进行判断是否相等。
public boolean isFlipedString(String s1, String s2) {
if(s1.length() != s2.length()){
return false;
}
char[] ch1 = s1.toCharArray();
char[] ch2 = s2.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
return Arrays.equals(ch1,ch2);
}
题目 :移除重复节点。编写代码,移除为排序链表中的重复节点,保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
思路 :利用HashSet进程存储,达到去重的效果。
code
public ListNode removeDuplicateNodes(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode currentNode = head;
HashSet<Integer> set = new HashSet<>();
set.add(head.val);
while(currentNode.next != null){
if(set.add(currentNode.next.val)){
currentNode = currentNode.next;
}else{
currentNode.next = currentNode.next.next;//调过一个结点。
}
}
return head;
}