剑指offer

sort:
对数组A的0~n-1元素进行升序排序,只要写sort(A,A+n)即可;
对于向量V也一样,sort(v.begin(),v.end())即可。
c/c++中获取字符串长度。有以下函数:size()、sizeof() 、strlen()、str.length();
每次记得初始化一维数组
int dp[60];
memset(dp,0,sizeof(dp));
或者int dp[60]={0};
split()
String[] arr = "11,22,33,44".splite(",");
从而方便的得到一个字符串数组:arr={"11", "22", "33", "44"};

 

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        unordered_map<int,int>map;
        for(int i:nums){
            map[i]++;
            if(map[i]==2){
                return i;
            }
        }
        return -1;
    }
};

 

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int i=matrix.size()-1,j=0;
        while(i>=0&&j<matrix[0].size()){
            if(matrix[i][j]==target) return true;
            else if(matrix[i][j]>target) i--;
            else j++;
        }
        return false;
    }
};

 

class Solution {
public:
    string replaceSpace(string s) {
        string res;
        for(char ch:s){
            if(ch==' ')
                res+="%20";
            else
                res+=ch;
        }
        return res;
    }
};

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    vector<int> reversePrint(ListNode* head) {
        if(head==NULL) return res;
        reversePrint(head->next);
        res.push_back(head->val);
        return res;
    }
};
//a.push_back(5); //在a的最后一个向量后插入一个元素,其值为5

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int len=preorder.length;
        if(len==0) return null;
        TreeNode node=new TreeNode(preorder[0]);
        for(int i=0;i<len;i++){
            if(inorder[i]==preorder[0]){
                node.left=buildTree(Arrays.copyOfRange(preorder,1,i+1),                             Arrays.copyOfRange(inorder,0,i));
                node.right=buildTree(Arrays.copyOfRange(preorder,i+1,len),
                Arrays.copyOfRange(inorder,i+1,len));
            }
        }
        return node;
    }
} 

 

class Solution {
public:
    int fib(int n) {
        if(n<2) return n;
        int dp[n+1];
        dp[0]=0;
        dp[1]=1;
        for(int i=2;i<=n;i++){
            dp[i]=(dp[i-1]+dp[i-2])%1000000007;
        }
        return dp[n];
    }
};

 

class Solution {
public:
    int rectCover(int number) {
        int dp[number+1];
        dp[1]=1;
        dp[2]=2;
        if(number<=3) return number;
        for(int i=3;i<=number;i++){
            dp[i]=dp[i-1]+dp[i-2];
        }
        return dp[number];
    }
};

#include<cmath>
class Solution {
public:
    int jumpFloorII(int number) {
        return (int) pow(2,number-1);
    }
};

class Solution {
public:
    int minNumberInRotateArray(vector<int> rotateArray) {
        if(rotateArray.size()==0) return 0;
        sort(rotateArray.begin(),rotateArray.end());
        return rotateArray[0];
    }
};

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[0].size();j++){
                if(dfs(board,word,i,j,0)) return true;
            }
        }
        return false;
    }
    bool dfs(vector<vector<char>>&board,string world,int i,int j,int k){
        if(i>=board.size()||i<0||j>=board[0].size()||j<0||board[i][j]!=world[k]) return false;
        if(k==world.length()-1) return true;
        char tmp=board[i][j];
        board[i][j]='/';
        bool res=dfs(board,world,i+1,j,k+1)||dfs(board,world,i-1,j,k+1)
        ||dfs(board,world,i,j+1,k+1)||dfs(board,world,i,j-1,k+1);
        board[i][j]=tmp;
        return res;
    }
};

class Solution {
public:
    int visited[101][101];
    int movingCount(int m, int n, int k) {     
        return dfs(0,0,m,n,k);
    }
    int dfs(int i,int j,int m,int n,int k){
        if(i<0||i>=m||j<0||j>=n||(i/10+i%10+j/10+j%10)>k||visited[i][j]==1)
            return 0;
        visited[i][j]=1;    
        return 1+dfs(i+1,j,m,n,k)+dfs(i,j+1,m,n,k);    
    }
};

 

class Solution {
public:
    int cuttingRope(int n) {
        int dp[60];
        memset(dp,0,sizeof(dp));
        dp[1]=1;
        dp[2]=1;
        for (int i = 2; i <= n; i++)
            for (int j = 1; j < i; j++){
                dp[i]=max(dp[i],max(j*dp[i-j],j*(i-j)));
            }
        return dp[n];
    }
};

 

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int cnt=0;
        while(n!=0){
            n=n&(n-1);
            cnt++;
        }
        return cnt;
    }
};

class Solution {
public:
    double myPow(double x, int n) {
        double res;
        if(n==0) return 1;
        if(n==1) return x;
        if(n==-1) return 1/x;
        if(n%2==0){
            double t=myPow(x,n/2);
            res= t*t;
        }
        else{
            double t=myPow(x,n/2);
            if(n<0) x=1/x;
            res= t*t*x;
        }
        return res;
    }
};

 

class Solution {
public:
    vector<int>res;
    vector<int> printNumbers(int n) {
        for(int i=1;i<pow(10,n);i++)
            res.push_back(i);
        return res;    
    }
};

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(!head) return NULL;
        if(head->val==val) return head->next;
        head->next=deleteNode(head->next,val);
        return head;
    }
};

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(head==NULL) return NULL;
        if(head->val==val) return head->next;
        ListNode *dummy=head;
        while(head&&head->next){
            if(head->next->val==val){
                head->next=head->next->next;
            }
            else{
                head=head->next;
            }
        }
        return dummy;
    }
};

 

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead==null||pHead.next==null) return pHead;
        if(pHead.val==pHead.next.val){
            ListNode node=pHead.next;
            // 跳过值与当前节点相同的全部节点,找到第一个与当前节点不同的节点
            while(node!=null&&node.val==pHead.val) node=node.next;
            return deleteDuplication(node);    
        }
        else{
            // 保留当前节点,从下一个节点继续递归
            pHead.next=deleteDuplication(pHead.next);
            return pHead;
        } 
    }
}

 

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int i=0,j=nums.size()-1;
        while(i<j){
            while(i<j&&nums[i]%2==1) i++;
            while(i<j&&nums[j]%2==0) j--;
            int tmp=nums[i];
            nums[i]=nums[j];
            nums[j]=tmp;
        }
        return nums;
    }
};

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        if(!head||k==0) return NULL;
        ListNode *fast=head,*low=head;
        for(int i=1;i<=k;i++){
            if(fast==NULL) return NULL; 
            fast=fast->next;
        }
        while(fast!=NULL){
            fast=fast->next;
            low=low->next;
        }
        return low;

    }
};

 

class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head==null||k==0) return null;
        ListNode fast=head,low=head;
        for(int i=0;i<k;i++){
            if(fast==null) return null;
            fast=fast.next;
        }
        while(fast!=null){
            fast=fast.next;
            low=low.next;
        }
        return low;
    }
}

class Solution {
    public ListNode reverseList(ListNode head) {
        //递归终止条件是当前为空,或者下一个节点为空
		if(head==null || head.next==null) {
			return head;
		}
		//这里的cur就是最后一个节点
		ListNode cur = reverseList(head.next);
		//这里请配合动画演示理解
		//如果链表是 1->2->3->4->5,那么此时的cur就是5
		//而head是4,head的下一个是5,下下一个是空
		//所以head.next.next=head 就是5->4
		head.next.next = head;
		//防止链表循环,需要将head.next设置为空
		head.next = null;
		//每层递归函数都返回cur,也就是最后一个节点
		return cur;
    }
}

 

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        if(l1.val<l2.val){
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }
        else{
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
}

 

class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if(A==null||B==null) return false;
        if(isPartSame(A,B)) return true;
        return isSubStructure(A.left,B)||isSubStructure(A.right,B);
    }
    boolean isPartSame(TreeNode A,TreeNode B){
        if(B==null) return true;
        if(A==null) return false;
        if(A.val==B.val){
            return isPartSame(A.left,B.left)&&isPartSame(A.right,B.right);
        }
        return false;
    }
}

 

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return null;
        TreeNode tmp;
        tmp=root.left;
        root.left=root.right;
        root.right=tmp;
        mirrorTree(root.left);
        mirrorTree(root.right);
        return root;
    }
}

 

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return isMirror(root.left,root.right);       
    }
    public boolean isMirror(TreeNode A,TreeNode B){
        if(A==null&&B==null) return true;
        else if(A==null||B==null||A.val!=B.val) return false;
        return isMirror(A.left,B.right)&&isMirror(A.right,B.left);
    }
}

LeetCode【1004】最大连续1的个数 III

public static int longestOnes(int[] A, int K) {
        int left = 0, right = 0;
        int max = 0;
        int zero = 0;
        while (right != A.length) {
            if (A[right++] == 0) {
                zero++;
            }
            //判定条件,0的个数大于K
            while (zero > K) {
                if (A[left++] == 0) {
                    --zero;
                }
            }
            int count = right - left;
            max = max > count ? max : count;
        }
        return max;
    }

 

import java.util.*;
public class Test1 {
    public static void main(String[] args) {
        //1.读取数据
        String str = new Scanner(System.in).nextLine();
        //2.统计种类数
        if (str.length()==0) return;
        char chars[] = str.toCharArray();
        char c = chars[0];
        int count=1;
        for (int i = 1; i < chars.length; i++) {
            if (chars[i]!=c) {
                count++;
                c = chars[i];
            }
        }
        //3.计算平均长度
        double avg = ((double)str.length()/count);
        System.out.println(avg);
    }
}

class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer>map=new HashMap<>();
        for(int num:nums){
            if(map.containsKey(num)){
                map.put(num,map.get(num)+1);
            }
            else{
                map.put(num,1);
            }
        }
        for(int key:map.keySet()){
            if(map.get(key)>nums.length/2){
                return key;
            }   
        }
        return -1;
    }
}

 

class Solution {
    public int longestOnes(int[] A, int K) {
        int right=0,left=0,max=0,zero=0;
        while(right!=A.length){
            if(A[right++]==0){
                zero++;
            }
            while(zero>K){
                if(A[left++]==0){
                    zero--;
                }
            }
            int cnt=right-left;
            max=max>cnt?max:cnt;
        }
        return max;
    }
}
//https://blog.csdn.net/qq422243639/article/details/98455642

class Solution {
    public char firstUniqChar(String s) {
        char []ch=s.toCharArray();
        int []mp=new int[128];
        for(char c:ch){
            mp[c]++;
        }
        for(char c:ch){
            if(mp[c]==1)
                return c;
        }
        return ' ';
    }
}

 

class Solution {
    public int maxSubArray(int[] nums) {
        int res=nums[0];
        int []dp=new int[nums.length];
        dp[0]=nums[0];
        for(int i=1;i<nums.length;i++){
            dp[i]=Math.max(dp[i-1]+nums[i],nums[i]);
            res=Math.max(res,dp[i]);
        }
        return res;     
    }
}

class Solution {
    public String minNumber(int[] nums) {
        String []str=new String[nums.length];
        for(int i=0;i<nums.length;i++){
            str[i]=String.valueOf(nums[i]);
        }
        Arrays.sort(str,(x,y)->(x+y).compareTo(y+x));
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<nums.length;i++){
            sb.append(str[i]);
        }
        return sb.toString();
    }
}

 

class Solution {
    public int translateNum(int num) {
        char []ch=String.valueOf(num).toCharArray();
        int len=ch.length;
        int []dp=new int[len+1];
        dp[0]=1;
        dp[1]=1;
        for(int i=2;i<=len;i++){
            int a=(ch[i-2]-'0')*10+(ch[i-1]-'0');
            if(a>=10&&a<=25)
                dp[i]=dp[i-1]+dp[i-2];
            else dp[i]=dp[i-1];
        }    
        return dp[len];
    }
}

 

class Solution {
    public int maxValue(int[][] grid) {
        int m=grid.length,n=grid[0].length;
        int [][]dp=new int[m][n];
        dp[0][0]=grid[0][0];
        for(int i=1;i<m;i++)
            dp[i][0]=dp[i-1][0]+grid[i][0];
        for(int i=1;i<n;i++)
            dp[0][i]=dp[0][i-1]+grid[0][i];
        for(int i=1;i<m;i++){
            for(int j=1;j<n;j++){
                dp[i][j]=Math.max(dp[i][j-1],dp[i-1][j])+grid[i][j];
            }
        }
        return dp[m-1][n-1];        

    }
}

 

 

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int left=0,right=0,res=0;
        HashSet<Character>set =new HashSet<>();
        while(right!=s.length()){
            char c=s.charAt(right++);
            while(set.contains(c)){
                set.remove(s.charAt(left++));
            }
            set.add(c);
            res=Math.max(res,right-left);
        }
        return res;
    }
}
//滑动窗口
//https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/solution/hua-dong-chuang-kou-by-eager-2/

 

class Solution {
    public int nthUglyNumber(int n) {
        int a=0,b=0,c=0;
        int n2=0,n3=0,n5=0;
        int []dp=new int[n];
        dp[0]=1;
        for(int i=1;i<n;i++){
            n2=2*dp[a];
            n3=3*dp[b];
            n5=5*dp[c];
            dp[i]=Math.min(Math.min(n2,n3),n5);
            if(dp[i]==n2) a++;
            if(dp[i]==n3) b++;
            if(dp[i]==n5) c++;
        }
        return dp[n-1];
    }
}

 

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode h1=headA,h2=headB;
        while(h1!=h2){
            h1=h1==null?headB:h1.next;
            h2=h2==null?headA:h2.next;
        }
        return h1;
    }
}

 

class Solution {
    public int[] singleNumbers(int[] nums) {
        HashSet<Integer>set=new HashSet<>();
        for(var num:nums){
            if(set.contains(num))
                set.remove(num);
            else set.add(num);    
        }
        int []res=new int[2];
        int i=0;
        for(var num:set){
            res[i++]=num;
        }
        return res;
    }
}

 

class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer,Integer> mp=new HashMap<>();
        for(var num:nums){
            if(mp.get(num)!=null)
                mp.put(num,mp.get(num)+1);
            else
                mp.put(num,1);    
        }
        for(var num:nums){
            if(mp.get(num)==1)
                return num;
        }
        return -1;

    }
}

 

class Solution {
    public int minDistance(String word1, String word2) {
        int m=word1.length();
        int n=word2.length();
        int [][]dp=new int[m+1][n+1];
        for(int i=0;i<=m;i++)
            dp[i][0]=i;
        for(int i=0;i<=n;i++)
            dp[0][i]=i;
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
                if(word1.charAt(i-1)==word2.charAt(j-1)){
                    dp[i][j]=dp[i-1][j-1];
                }
                else{
                    dp[i][j]=1+Math.min(Math.min(dp[i][j-1],dp[i-1][j]),dp[i-1][j-1]);
                }
            }
        }
        return dp[m][n];
    }
}

class Solution {
    public int[] singleNumbers(int[] nums) {
        HashMap<Integer,Integer>mp=new HashMap<>();
        for(var num:nums){
            if(mp.get(num)!=null){
                mp.put(num,mp.get(num)+1);
            }
            else{
                mp.put(num,1);
            }
        }
        int []res=new int[2];
        int i=0;
        for(var num:nums){
            if(mp.get(num)==1){
                res[i++]=num;
            }
        }
        return res;

    }
}

 

class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer,Integer> mp=new HashMap<>();
        for(var num:nums){
            if(mp.get(num)!=null)
                mp.put(num,mp.get(num)+1);
            else
                mp.put(num,1);    
        }
        for(var num:nums){
            if(mp.get(num)==1)
                return num;
        }
        return -1;

    }
}

 

class Solution {
    public char firstUniqChar(String s) {
        char []ch=s.toCharArray();
        HashMap<Character,Integer>mp=new HashMap<>();
        for(char c:ch){
            if(mp.get(c)!=null){
                mp.put(c,mp.get(c)+1);
            }
            else{
                mp.put(c,1);
            }
        }
        for(char c:ch){
            if(mp.get(c)==1)
                return c;
        }
        return ' ';
    }
}

 

class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer>map=new HashMap<>();
        for(int num:nums){
            if(map.containsKey(num)){
                map.put(num,map.get(num)+1);
            }
            else{
                map.put(num,1);
            }
        }
        for(int key:map.keySet()){
            if(map.get(key)>nums.length/2){
                return key;
            }   
        }
        return -1;
    }
}

 

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int i=0,j=nums.length-1;
        for(;i<j;){
            if(nums[i]+nums[j]==target)
                return new int[]{nums[i],nums[j]};
            else if(nums[i]+nums[j]<target) i++;
            else j--;
        }
        return new int[]{0,0};
    }
}

 

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        vector<vector<int>> res;
        int i=1,j=1,sum=0;
        while(i<=target/2){
            if(sum<target){
                sum+=j;
                j++;
            }
            else if(sum>target){
                sum-=i;
                i++;
            }
            else{
                vector<int> arr;
                for(int k=i;k<j;k++){
                    arr.push_back(k);
                }
                res.push_back(arr);
                sum-=i;
                i++;
            }         
        }
        return res;
    }
};

 

class Solution {
    public int[][] findContinuousSequence(int target) {
        List<int []>res=new ArrayList<>();
        int i=1,j=1,sum=0;
        while(i<=target/2){
            if(sum<target){
                sum+=j;
                j++;
            }
            else if(sum>target){
                sum-=i;
                i++;
            }
            else{
                int []a=new int[j-i];
                for(int k=i;k<j;k++){
                    a[k-i]=k;
                }
                res.add(a);
                sum-=i;
                i++;
            }
        }
        return res.toArray(new int[0][]);
    }
}

class Solution {
    public String reverseWords(String s) {
        String []str=s.trim().split(" ");
        int len=str.length;
        StringBuilder sb=new StringBuilder();
        for(int i=len-1;i>=0;i--){
            if(str[i].equals("")) continue;
            sb.append(str[i]+" ");
        }
        return sb.toString().trim();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值