142. 环形链表 II(中等)
思路:快慢指针,相遇 的时候意味着快比慢多走了一个圆环路程,但是怎么确定圆环入口忘记了,直接用 set 判断重复的。后来发现是需要把 head 移动,当 head 入环的时候慢指针刚好回到入口。文章来源:https://www.toymoban.com/news/detail-599045.html
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(slow!=null && fast != null){
fast = fast.next;
if(fast!=null)fast=fast.next;
else return null;
slow = slow.next;
if(slow == fast){
while(head!=slow){
head = head.next;
slow = slow.next;
}
return head;
}
}
return null;
}
}
剑指 Offer II 070. 排序数组中只出现一次的数字(中等)
// 思路:取异或
class Solution {
public int singleNonDuplicate(int[] nums) {
int sum = nums[0];
for(int i =1;i<nums.length;i++)
sum = sum^nums[i];
return sum;
}
}
78. 子集(中等)
class Solution {
public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;
List<List<Integer>> res = new ArrayList<>();
dfs(nums,0,new ArrayList<>(),res);
return res;
}
public void dfs(int nums[],int it,List<Integer> temp,List<List<Integer>> res){
if(it>=nums.length){
res.add(new ArrayList<>(temp));
return ;
}
dfs(nums,it+1,temp,res);
temp.add(nums[it]);
dfs(nums,it+1,temp,res);
temp.remove(temp.size()-1);
}
}
902. 最大为 N 的数字组合(困难)
class Solution {
public int atMostNGivenDigitSet(String[] digits, int n) {
String num = String.valueOf(n);
int m = num.length();
int l = digits.length;
int cnt = 0;
int record[] = new int[m+1];
for(int i=1;i<=m;i++){
record[i] = (int)Math.pow(l,i);
if(i<m)cnt+=record[i];
}
return dfs(num,digits)+cnt;
}
public int dfs(String num,String digits[]){
int cnt = 0;
int l = digits.length,n = num.length();
if(n == 0)return 1;
for(int i = 0;i<l;i++){
if(digits[i].charAt(0)<num.charAt(0)){
cnt += (int)Math.pow(l,n-1);
}else if(digits[i].charAt(0)==num.charAt(0)){
cnt += dfs(num.substring(1),digits);
}else{
break;
}
}
return cnt;
}
}
143. 重排链表(中等)
思路:用数组辅助;或者找到中点,反转后半部分,在合并起来文章来源地址https://www.toymoban.com/news/detail-599045.html
class Solution {
public void reorderList(ListNode head) {
ListNode it = head.next;
List<ListNode> li = new ArrayList<>();
while(it!=null){
li.add(it);
it = it.next;
}
int n = li.size();
if(n==0)return ;
it = head;
for(int i=0;i<=(n-1)/2;i++){
it.next = li.get(n-1-i);
it = li.get(n-1-i);
if(n-1-i!=i){
it.next = li.get(i);
it = li.get(i);
}
}
it.next = null;
}
}
到了这里,关于LeetCode(字节10日)-0717的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!