T2(反转偶数长度组链表结点-待补充)
- 这道题卡的时间挺久
- 存储翻转元素,并在偶数长度部分翻转
- 教训:一定要想清楚每次进入循环中不变的是什么东西,即设置好循环不变量
- 例如此题的循环不变量:进入迭代cur指向某组的第一个元素
- 否则会十分混乱
- 并且注意题目中所说的是偶数长度的组,和偶数组不是一回事
- 最后一组的组序号也许是
class Solution {
public ListNode reverseEvenLengthGroups(ListNode head) {
ListNode cur = head;
int i = 1;
//循环不变量:每次进入循环时cur始终指向某个组的第一个元素
//i用于记录当前组元素的个数
while(cur!=null)
{
int actual_len = 0;
List<ListNode> a = new ArrayList<>();
while(cur!=null && actual_len <= i - 1)
{
actual_len++;
a.add(cur);
cur = cur.next;
}
if(a.size()%2 == 0)
reverse(a);
i++;
}
return head;
}
}
T3-解码斜向换位密码
- 这道题是一道十分简单的模拟题。老是超时,
- 结果发现去掉tostring()方法即可
- 说明了tostring方法可能需要线性的时间执行
class Solution {
public String decodeCiphertext(String encodedText, int rows)
{
int len = encodedText.length();
//列数
int cols = len / rows;
StringBuilder ans = new StringBuilder();
for(int i = 0;i<cols;i++)
{
int p = 0;
int q = i;
while(p<rows && q<cols)
{
ans.append(encodedText.charAt(p * cols + q));
p++;
q++;
}
}
int j;
for( j = ans.toString().length() - 1;j>=0 && ans.charAt(j) == ' ';j--);
return ans.toString().substring(0,j+1);
}
}
T4(并查集)-处理含限制条件的好友请求
- 未经优化的暴力代码
- 教训:这道题也卡了很久,原因是自以为是的不画对象图
- 注意java中对象元素的引用和复制!对象数组中
class Solution {
public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {
Map<Integer,Set<Integer>> restrict = new HashMap<>();
for(int i = 0;i<n;i++)
restrict.put(i,new HashSet<>());
//不能成为朋友的集合
for(int[] relation : restrictions)
{
restrict.get(relation[0]).add(relation[1]);
restrict.get(relation[1]).add(relation[0]);
}
Set[] a = new Set[n];
for(int i = 0;i<a.length;i++) {
a[i] = new HashSet<Integer>();
a[i].add(i);
}
boolean[] ret = new boolean[requests.length];
int cout = 0;
for(int[] j : requests)
{
boolean flag = true;
for(int p : (Set<Integer>)a[j[0]])
{
for(int q : (Set<Integer>)a[j[1]])
{
if(restrict.get(p).contains(q))
{
flag = false;
break;
}
}
if(!flag)
break;
}
if(flag)
{
a[j[0]].addAll(a[j[1]]);
for(int p : (Set<Integer>)a[j[1]]) //注意,这里当时卡了很长时间
//原因就是没有使得a[j[1]]的所有元素指向这个集合
a[p] = a[j[0]];
}
ret[cout++] = flag;
}
return ret;
}
}