LeetCode21~40题——NWU_LK

LeetCode第21题

合并两个有序链表

public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode p=l1;
        ListNode q=l2;
        ListNode l3=new ListNode();
        ListNode result=l3;
        while (q!=null & p!=null){
            if (p.val<q.val){
                result.next=p;
                result=p;
                p=p.next;
            }else {
                result.next=q;
                result=q;
                q=q.next;
            }
        }
        if (q!=null){
            result.next=q;
            result=q;
            q=q.next;
        }
        if (p!=null){
            result.next=p;
            result=p;
            p=p.next;
        }
        return l3.next;
    }
}

LeetCode第22题

括号生成:暴力解法

class Solution {
    private List<String> result=new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        char[] kuohao=new char[n*2];
        traceback(kuohao,0);
        return result;
    }
    public void traceback(char kuohao[],int index){
        if (index==kuohao.length){
            if (match(kuohao)){
                result.add(new String(kuohao));
            }
        }else {
            kuohao[index]='(';
            traceback(kuohao,index+1);
            kuohao[index]=')';
            traceback(kuohao,index+1);
        }
    }
    public boolean match(char[] kuohao){
        int x=0;
        for (int i=0;i<kuohao.length;i++){
            if (kuohao[i]=='('){
                x++;
            }else {
                x--;
            }
            if (x<0){
                return false;
            }
        }
        return x==0;
    }
}

LeetCode第23题

合并k个有序链表

//链表结构
public class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }  
}
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        int len=lists.length;
        if (len == 0) {
            return null;
        }
        while (len>1){
            for (int i=0;i<(len/2);i++){
                lists[i]=mergeTwoLists(lists[i],lists[len-i-1]);
            }
            len=(len+1)/2;
        }
        return lists[0];
    }
   public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode p = head;
        while(l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        if (l1 != null) {
            p.next = l1;
        } else if (l2 != null) {
            p.next = l2;
        }
        return head.next;
    }
}

LeetCode第24题

两两交换链表中的节点

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head==null||head.next==null){
            return head;
        }
        ListNode p=head;
        ListNode q=head.next;
        ListNode pre=null;
        while (q!=null){
            if (pre==null){
                head=q;
                p.next=q.next;
                q.next=p;
                pre=p;
                p=p.next;
                if (p!=null){
                    q=p.next;
                }else {
                    q=null;
                }
                continue;
            }
            ListNode tmp=q.next;
            q.next=p;
            p.next=tmp;
            pre.next=q;
            pre=p;
            p=p.next;
            if (p!=null){
                q=p.next;
            }else {
                q=null;
            }
        }
        return head;
    }
}

LeetCode第25题

K 个一组翻转链表

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (k<=1){
            return head;
        }
        Stack<ListNode> stack=new Stack<>();
        ListNode newNode=new ListNode(-1);
        ListNode p=head;
        ListNode q=newNode;
        int num=0;
        while (p!=null){
            num++;
            stack.push(p);
            p=p.next;
            if (num==k){
                while (!stack.empty()){
                    ListNode pop = stack.pop();
                    pop.next=null;
                    q.next=pop;
                    q=pop;
                }
                num=0;
            }
        }
        if (!stack.isEmpty()){
            q.next=stack.remove(0);
        }
        return newNode.next;
    }
}

LeetCode第26题

删除排序数组中的重复项

class Solution {
    public int removeDuplicates(int[] nums) {
        int len=nums.length;
        if (len<2){
            return len;
        }
        int i=0,j=0;
        while(i!=len){
            nums[j++]=nums[i++];
            while (i!=len && nums[i]==nums[i-1]){
                i++;
            }
        }
        return j;
    }
}

LeetCode第27题

移除元素

class Solution {
    public int removeElement(int[] nums, int val) {
        int j=0;
        for(int i=0;i<nums.length;i++){
            if (nums[i]!=val){
                nums[j++]=nums[i];
            }
        }
        return j;
    }
}

LeetCode第28题

实现strStr()

class Solution {
    public int strStr(String haystack, String needle) {
        int p=0,q=0;
        int start=0;
        p=start;
        while (p!=haystack.length()&&q!=needle.length()){
            if (haystack.charAt(p)==needle.charAt(q)){
                p++;
                q++;
            }else {
                start++;
                p=start;
                q=0;
            }
        }
        if (q==needle.length()){
            return start;
        }else {
            return -1;
        }
    }
}

LeetCode第29题

两数相除:超时了

class Solution {
    public int divide(int dividend, int divisor) {
        boolean flag=dividend>0==divisor>0;
        if (dividend>0){
            dividend=(-dividend);
        }
        if (divisor>0){
            divisor=(-divisor);
        }
        if (divisor<dividend){
            return 0;
        }
        int result=divisor;
        long count=1;
        while (result>dividend){
            result+=divisor;
            count++;
        }
        if (result!=dividend){
            count--;
        }
        if (!flag){   //需要转换为负数
            count=(-count);
        }
        if (count>Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        return (int)count;
    }
}

LeetCode第30题

串联所有单词的子串

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> result=new ArrayList<>();
        if (words==null||words.length==0)
            return result;
        int word_count=words.length;
        int word_len=words[0].length();
        //将words每个单词及其个数存入map
        HashMap<String,Integer> map=new HashMap<>();
        for (String word:words){
            int value=map.getOrDefault(word,0);
            map.put(word,value+1);
        }
        for (int i=0;i<s.length()-word_count*word_len+1;i++){
            //统计子串中有几个单词匹配成功
            int count=0;
            //统计字串中出现的主串中的单词和频次
            Map<String,Integer> sub_map=new HashMap<>();
            //统计字串中连续和words中相等的单词
            while (count<word_count){
                String w=s.substring(i+count*word_len,i+(count+1)*word_len);
                //如果word匹配words中的单词,就统计其出现次数
                if (map.containsKey(w)){
                    int v=sub_map.getOrDefault(w,0);
                    sub_map.put(w,v+1);
                    //如果word出现次数超过words中这个单词的总数量则结束统计
                    if (sub_map.get(w)>map.get(w)){
                        break;
                    }
                }else {
                    //如果字串中出现于words中所有单词都不匹配的word则结束统计
                    break;
                }
                //增加成功与words中匹配的单词数量
                count++;
            }
            if (count==word_count){
                result.add(i);
            }
        }
        return result;
    }
}

LeetCode第31题

下一个排序

class Solution {
    public void nextPermutation(int[] nums) {
        boolean flag=false;
        for (int i=nums.length-2;i>=0;i--){
            if (nums[i]>=nums[i+1]){
                continue;
            }
            flag=true;
            int j=nums.length-1;
            while (nums[j]<=nums[i]){
                j--;
            }
            int tmp=nums[i];
            nums[i]=nums[j];
            nums[j]=tmp;
            Arrays.sort(nums,i+1,nums.length);
            break;
        }
        if (!flag){
            Arrays.sort(nums);
        }
    }
}

LeetCode第32题

最长有序括号

class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> stack=new Stack<>();
        stack.push(-1);
        int maxLen=0;
        int len=s.length();
        for (int i=0;i<len;i++){
            if ('('==s.charAt(i)){
                stack.push(i);
            }else {
                stack.pop();
                if (stack.empty()){
                    stack.push(i);
                }else {
                    maxLen=Math.max(maxLen,i-stack.peek());
                }
            }
        }
        return maxLen;
    }
}

LeetCode第33题

搜索旋转排序数组

class Solution {
    public int search(int[] nums, int target) {
        int low=0,high=nums.length-1;
        while (low<=high){
            int mid=(low+high)/2;
            if (nums[mid]==target)
                return mid;
            if (nums[mid]<nums[high]){
                if (target>nums[mid]&&target<=nums[high]){
                    low=mid+1;
                }else {
                    high=mid-1;
                }
            }else{
                if (target<nums[mid]&&target>=nums[low]){
                    high=mid-1;
                }else {
                    low=mid+1;
                }
            }
        }
        return -1;
    }
}

LeetCode第34题

在排序数组中查找元素的第一个和最后一个位置。
思路:因为要求时间复杂度为O(logn),所以直接用折半查找,找到目标元素后再去求其两个边界位置。

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result=new int[]{-1,-1};
        int low=0,high=nums.length-1;
        while (low<=high){
            int mid=(low+high)/2;
            if (nums[mid]==target){
            	//用来记录目标值最左边的位置
                int left=mid;
                //用来记录目标值最左右边的位置
                int right=mid;
                while (left-1>=low&&nums[left-1]==nums[mid]){
                    left--;
                }
                while (right+1<=high&&nums[right+1]==nums[mid]){
                    right++;
                }
                result[0]=left;
                result[1]=right;
                return result;
            }else if (nums[mid]<target){
                low=mid+1;
            }else{
                high=mid-1;
            }
        }
        return result;
    }
}

LeetCode第35题

搜索插入位置,直接二分查找

class Solution {
    public int searchInsert(int[] nums, int target) {
        int result=0;
        int low=0,high=nums.length-1;
        while (low<=high){
            int mid=(low+high)/2;
            if (nums[mid]==target){
                return mid;
            }else if (nums[mid]<target){
                if (target<nums[mid+1])
                    return mid;
                low=mid+1;
            }else{
                if (target>nums[mid-1])
                    return mid-1;
                high=mid-1;
            }
        }
        if (low>nums.length-1)
            return low;
        return 0;
    }
}

LeetCode第36题

有效的数独

class Solution {
    public boolean isValidSudoku(char[][] board) {
    	//记录每一行、每一列、每个块是否出现过某个值
        boolean[][] row=new boolean[9][9];
        boolean[][] col=new boolean[9][9];
        boolean[][] block=new boolean[9][9];
        for (int i=0;i<block.length;i++){
            for (int j=0;j<block.length;j++){
                if (board[i][j]!='.'){
                    int num=board[i][j]-'1';
                    //判断在第几个块0-8
                    int blockIndex=i/3*3+j/3;
                    if (row[i][num]||col[j][num]||block[blockIndex][num]){
                        return false;
                    }else {
                        row[i][num]=true;
                        col[j][num]=true;
                        block[blockIndex][num]=true;
                    }
                }
            }
        }
        return true;
    }
}

LeetCode第37题

解数独:回溯法(递归)

class Solution {
    public void solveSudoku(char[][] board) {
        boolean[][] row=new boolean[9][9];
        boolean[][] col=new boolean[9][9];
        boolean[][] block=new boolean[9][9];
        for (int i=0;i<block.length;i++){
            for (int j=0;j<block.length;j++){
                if (board[i][j]!='.'){
                    int num=board[i][j]-'1';
                    //判断在第几个块0-8
                    int blockIndex=i/3*3+j/3;
                    row[i][num]=true;
                    col[j][num]=true;
                    block[blockIndex][num]=true;
                }
            }
        }
        dfs(board,row,col,block,0,0);
    }
     public boolean dfs(char[][] board, boolean[][] row, boolean[][] col, boolean[][] block, int i, int j) {
        //寻找插入位置
        while (board[i][j]!='.'){
            j++;
            if (j>=9){
                i++;j=0;
            }
            if (i>=9){
                return true;
            }
        }
        for (int num=0;num<=8;num++){
            int blockIndex = i / 3 * 3 + j / 3;
            if (!row[i][num]&&!col[j][num]&&!block[blockIndex][num]){
                board[i][j]=(char)('1'+num);
                row[i][num]=true;
                col[j][num]=true;
                block[blockIndex][num]=true;
                if (dfs(board,row,col,block,i,j))
                    return true;
                else {
                    board[i][j]='.';
                    row[i][num]=false;
                    col[j][num]=false;
                    block[blockIndex][num]=false;
                }
            }
        }
        return false;
    }
}

LeetCode第38题

外观数列

class Solution {
    public String countAndSay(int n) {
        String x="1";
        for (int i=1;i<n;i++){
            int index=0;
            int count=1;
            int len=x.length();
            StringBuilder sb=new StringBuilder();
            while (index<len){
                char c=x.charAt(index);
                if (index+1<len && c==x.charAt(index+1)){
                    count++;index++;continue;
                }
                sb.append(count);
                sb.append(c);
                count=1;
                index++;
            }
            x=sb.toString();
        }
        return x;
    }
}

LeetCode第39题

组合总和:回溯法(递归)

class Solution {
    private List<List<Integer>> result=new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<Integer> list=new ArrayList<>();
        dfs(candidates,target,list,0,0);
        return result;
    }
    public void dfs(int[] candidates, int target, List<Integer> list,int sum,int index){
        if (sum==target){
            result.add(new ArrayList<>(list));
            return;
        }
        if (sum>target){
            return;
        }
        while (index<candidates.length){
            list.add(candidates[index]);
            sum+=candidates[index];
            dfs(candidates,target,list,sum,index);
            sum-=candidates[index];
            list.remove(list.size()-1);
            index++;
        }
    }
}

LeetCode第39题

组合总和:回溯法(递归)

class Solution {
    private List<List<Integer>> result=new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<Integer> list=new ArrayList<>();
        dfs(candidates,target,list,0,0);
        return result;
    }
    public void dfs(int[] candidates, int target, List<Integer> list,int sum,int index){
        if (sum==target){
            result.add(new ArrayList<>(list));
            return;
        }
        if (sum>target){
            return;
        }
        while (index<candidates.length){
            list.add(candidates[index]);
            sum+=candidates[index];
            dfs(candidates,target,list,sum,index);
            sum-=candidates[index];
            list.remove(list.size()-1);
            index++;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值