42. 环形链表 II
找规律
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head, low = head;
while(fast != null){
low = low.next;
if(fast.next == null) return null;
fast = fast.next.next;
if(fast == low){
ListNode temp = head;
while(temp != low){
temp = temp.next;
low = low.next;
}
return temp;
}
}
return null;
}
}
141. 环形链表
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head, low = head;
if(fast == null || fast.next == null) return false;
while(fast != null){
low = low.next;
fast = fast.next;
if(fast != null) fast = fast.next;
if(fast == low) return true;
}
return false;
}
}
139. 单词拆分
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordDictSet = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 1; i <= s.length(); i++){
for(int j = 0; j < i; j++){
if(dp[j] && wordDictSet.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
136. 只出现一次的数字
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
result ^= nums[i];
}
return result;
}
}
647. 回文子串
class Solution {
public int countSubstrings(String s) {
int ans = 0;
for(int i = 0 ; i < s.length(); i++){
ans += get(s, i, i) + get(s, i, i + 1);
}
return ans;
}
public int get(String s, int l, int r){
int ans = 0;
while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)){
ans++;
l--;
r++;
}
return ans;
}
}
128. 最长连续序列
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> map = new HashSet<>();
for(int num : nums) map.add(num);
int ans = 0;
for(int num : map){
if(map.contains(num - 1)) continue;
int len = 1, now = num;
while(map.contains(now + 1)){
len++;
now++;
}
ans = Math.max(ans, len);
}
return ans;
}
}
9万+

被折叠的 条评论
为什么被折叠?



