Question:给定一个链表(链表结点包含一个整型值)的头结点 head。
同时给定列表 G,该列表是上述链表中整型值的一个子集。
返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。
//解题思路: 对链表进行遍历 拿到每个节点的整型值 与数组中的数一一比对,相同记为true 不同记录为false 将所有的记录结果拼接成字符串 得到的字符串类似于这样:
,true,true,true,false,false,true,false
然后将字符串 用 ”,false“ 进行切割 最后的到的字符串数组 即为
[",true,true,true"] ,[""],[",true"],[""]
然后对数组中的元素进行一下判断,筛出 内容为 空字符串的数组 返回内容不为空 的字符串数组个数即可。
class Solution {
public int numComponents(ListNode head, int[] G) {
String isSameStr="";
Boolean isSame = false;
int flag = 0;
while(head != null){
for(int i = 0;i < G.length;i++){
if(head.val == G[i]){
isSame = true;
break;
}
}
head = head.next;
isSameStr += ","+isSame;
isSame = false;
}
String[] str = isSameStr.split(",false");
for(int i = 0;i < str.length;i++){
flag = str[i].trim().equals("")?flag:flag+1;
}
return flag;
}
}
想想自己想到的解决方案还真是厉害呢!内存消耗居然击败了百分之0.00%的对手,此时我并没有坐在电脑前哭泣,此时的我开始想要知道,代码为什么内存消耗这样大(此前从未研究过)
原因1: isSameStr += “,”+isSame; 这是个什么鬼!!!!!
学过java的人都知道 每运行一次这个语句 内存中就会多一个String对象 由于java 虚拟机不仅要花时间生成对象,以后可能还要花时间对这些对象进行垃圾回收和处理。 (我写这段代码的时候,脑袋一定坏掉了。。。)
解决方案:使用StringBuilder 或者 StringBuffer
将原语句替换为:isSameStr.append(","+isSame); 内存消耗直接从 369.7 MB 到了 49MB 执行用时 2719 ms -》300ms
虽然击败的用户还是0.00%。。。。。
简单看了一下别人的解法,目前看到的基本都为 以空间换时间 我这什么都没换,内存消耗也没有比别人少,这就有些吃亏了。于是我苦心专研,研究了一下别人的方案。
class Solution {
public int numComponents(ListNode head, int[] G) {
int[] flag = new int[10000];
int isSame = 0;
int result = 0;
for(int i = 0 ; i < G.length; i++){
flag[G[i]] = 1;
}
while(head != null){
while(head != null && flag[head.val] == 1){
isSame = 1;
head = head.next;
}
if(isSame == 1){
result++;
isSame = 0;
}
if(head != null){
head = head.next;
}else{
return result;
}
}
return result;
}
}
研究后我觉得以后碰到类似的题 我也想不到这样的方案。。。。。