算法刷题记录(LeetCode 631-660)

633. Sum of Square Numbers

class Solution {
public:
    inline static double epsilon = 1e-5;
    bool judgeSquareSum(int c) {
        int limit = sqrt(c / 2);
        for (int i = 0; i <= limit; ++i) {
            int residual = c - i*i;
            double res = sqrt(residual);
            if (((double )ceil(res) - res)<epsilon){
                return true;
            }
        }
        return false;
    }
};

637. Average of Levels in Binary Tree

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
    vector<double> averageOfLevels(TreeNode* root) {
        queue<TreeNode*> currLayer;
        queue<TreeNode*> nextLayer;
        currLayer.push(root);
        vector<double> ans;
        while (!currLayer.empty()){
            double sum=0;
            auto cnt=currLayer.size();
            while (!currLayer.empty()){
                auto curr=currLayer.front();
                currLayer.pop();
                sum+=curr->val;
                if (curr->left){
                    nextLayer.push(curr->left);
                }
                if (curr->right){
                    nextLayer.push(curr->right);
                }
            }
            ans.push_back(sum/cnt);
            currLayer.swap(nextLayer);
        }
        return ans;
    }

640. Solve the Equation

class Solution {
    public static final Set<Character> operators=init_Set();
    public static final String INFINITE_SOLUTIONS="Infinite solutions";
    public static final String NO_SOLUTIONS="No solution";
    public static Set<Character> init_Set(){
        Set<Character> operators=new HashSet<>();
        operators.add('-');
        operators.add('+');
        operators.add('x');
        return operators;
    }
    public String solveEquation(String equation) {
        String[] twoSides=equation.split("=");
        int x_coff=0;
        int constant=0;
        int curr_dire=1;
        char[] left=twoSides[0].toCharArray();
        char[] right=twoSides[1].toCharArray();
        for (int i=0;i<left.length;i++){
            if (left[i]=='+'){
                curr_dire=1;
            }
            else if (left[i]=='-'){
                curr_dire=-1;
            }
            else{
                int j=i;
                while (j<left.length&&!operators.contains(left[j])){
                    j++;
                }
                if (j<left.length&&left[j]=='x'){
                    if (i==j){
                        x_coff+=curr_dire;
                        continue;
                    }
                    x_coff+=curr_dire*Integer.parseInt(twoSides[0].substring(i,j));
                    i=j;
                }
                else{
                    constant+=curr_dire*Integer.parseInt(twoSides[0].substring(i,j));
                    i=j-1;
                }
            }
        }
        curr_dire=-1;
        for (int i=0;i<right.length;i++){
            if (right[i]=='+'){
                curr_dire=-1;
            }
            else if (right[i]=='-'){
                curr_dire=1;
            }
            else{
                int j=i;
                while (j<right.length&&!operators.contains(right[j])){
                    j++;
                }
                if (j<right.length&& right[j]=='x'){
                    if (i==j){
                        x_coff+=curr_dire;
                        continue;
                    }
                    x_coff+=curr_dire*Integer.parseInt(twoSides[1].substring(i,j));
                    i=j;
                }
                else{
                    constant+=curr_dire*Integer.parseInt(twoSides[1].substring(i,j));
                    i=j-1;
                }
            }
        }
        if (x_coff==0){
            if (constant==0){
                return INFINITE_SOLUTIONS;
            }
            return NO_SOLUTIONS;
        }
        return "x="+(-constant/x_coff);
    }

}

641. Design Circular Deque

class MyCircularDeque {
public:
    int capacity = 0;
    vector<int> vec;
    int front = 0;
    int rear = 0;

    MyCircularDeque(int k) {
        capacity = k+1;
        vec.resize(capacity);
    }

    bool insertFront(int value) {
        if (isFull()){
            return false;
        }
        front=(front+capacity-1)%capacity;
        vec[front]=value;
        return true;
    }

    bool insertLast(int value) {
        if (isFull()){
            return false;
        }
        vec[rear]=value;
        rear=(rear+1)%capacity;
        return true;
    }

    bool deleteFront() {
        if (isEmpty()){
            return false;
        }
        front=(front+1)%capacity;
        return true;
    }

    bool deleteLast() {
        if (isEmpty()){
            return false;
        }
        rear=(rear-1+capacity)%capacity;
        return true;
    }

    int getFront() {
        if (isEmpty()){
            return -1;
        }
        return  vec[front];
    }

    int getRear() {
        if (isEmpty()){
            return -1;
        }
        return vec[(rear - 1 + capacity) % capacity];
    }

    bool isEmpty() {
        return front==rear;
    }

    bool isFull() {
        return (rear+1)%capacity==front;
    }
};

643. Maximum Average Subarray I

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        double ans = 0;
        double curr_max = Double.NEGATIVE_INFINITY;
        for (int i = 0; i < k - 1; i++) {
            ans += (double) nums[i] / k;
        }
        int left = 0;
        for (int i = k - 1; i < nums.length; i++) {
            ans += (double) nums[i] / k;
            curr_max = Math.max(curr_max, ans);
            ans -= (double) nums[left] / k;
            left++;
        }
        return curr_max;
    }
}

645. Set Mismatch

    vector<int> findErrorNums(vector<int>& nums) {
        vector<int> ans(2);
        for (int val:nums) {
            int target=abs(val)-1;
            if (nums[target]<0){
                ans[0]=target+1;
            }
            else{
                nums[target]=-nums[target];
            }
        }
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i]>0){
                ans[1]=i+1;
                return ans;
            }
        }
        return ans;
    }

646. Maximum Length of Pair Chain

贪心 其实就是最多子区间问题

    int findLongestChain(vector<vector<int>>& pairs) {
        std::sort(pairs.begin(), pairs.end(),[](auto a,auto b){
            if (a[1]!=b[1]){
                return a[1]<b[1];
            }
            return a[0]<b[0];
        });
        int curr_end=numeric_limits<int>::min();
        int res=0;
        for (auto & pair : pairs) {
            if (pair[0]>curr_end){
                curr_end=pair[1];
                res++;
            }
        }
        return res;
    }

648. Replace Words

Trie

class Solution {
    public static class PrefixTree {
        boolean end = false;
        HashMap<Character, PrefixTree> children = new HashMap<>();

        public void insert(PrefixTree tree, String _word) {
            char[] word = _word.toCharArray();
            PrefixTree curr = tree;
            for (char s : word) {
                if (!curr.children.containsKey(s)) {
                    curr.children.put(s, new PrefixTree());
                }
                curr = curr.children.get(s);
            }
            curr.end = true;
        }

        public String match(PrefixTree tree, String _word) {
            char[] word = _word.toCharArray();
            StringBuilder path = new StringBuilder();
            PrefixTree curr = tree;
            for (char ch : word) {
                path.append(ch);
                if (!curr.children.containsKey(ch)) {
                    return _word;
                }
                curr = curr.children.get(ch);
                if (curr.end) {
                    return path.toString();
                }
            }
            return _word;
        }
    }

    public String replaceWords(List<String> dictionary, String sentence) {
        PrefixTree tree = new PrefixTree();
        for (String word : dictionary) {
            tree.insert(tree, word);
        }
        StringBuilder res = new StringBuilder();
        String[] words = sentence.split(" ");
        for (String word : words) {
            res.append(tree.match(tree, word)).append(" ");

        }
        return res.toString().strip();
    }
}

650. 2 Keys Keyboard

DP

    int minSteps(int n) {
        int dp[1005];
        dp[0]=0;
        dp[1]=0;
        dp[2]=2;
        for (int i = 3; i <= n; ++i) {
            if (i%2==0) {
                dp[i] = dp[i / 2] + 2;
                continue;
            }
            dp[i]=i;
            for (int j = 3; j < n/2; ++j) {
                if (i%j==0){
                    dp[i]= min(dp[i],dp[j]+i/j);
                }
            }

        }
        return dp[n];
    }

*652. Find Duplicate Subtrees

利用前/中/后序遍历,将为null的节点置入null,判断是否存在相同结构

class Solution {
    public HashMap<String,Integer> alphabet=new HashMap<>();
    public List<TreeNode> res=new ArrayList<>();
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        dfs(root);
        return res;
    }
    public String dfs(TreeNode root){
        if (root==null){
            return "NULL";
        }
        String s=(root.val+","+dfs(root.left)+","+dfs(root.right));
        if (alphabet.getOrDefault(s,0)==1){
            res.add(root);
        }
        alphabet.put(s,alphabet.getOrDefault(s,0)+1);
        return s;

    }
}

653. Two Sum IV - Input is a BST

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        unordered_set<int> require;
        queue<TreeNode*> queue1;
        queue1.push(root);
        while (!queue1.empty()){
            auto curr=queue1.front();
            queue1.pop();
            if(require.count(curr->val)){
                return true;
            }
            else{
                require.insert(k-curr->val);
            }
            if (curr->left){
                queue1.push(curr->left);
            }
            if (curr->right){
                queue1.push(curr->right);
            }
        }
        return false;
    }
};

654. Maximum Binary Tree

class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return buildTree(nums,0,nums.length-1);
    }
    public TreeNode buildTree(int[] nums,int start,int end){
        if (start>end){
            return null;
        }
        int maxIdx=getMaxIdx(nums,start,end);
        TreeNode node=new TreeNode(nums[maxIdx]);
        node.left=buildTree(nums,start,maxIdx-1);
        node.right=buildTree(nums,maxIdx+1,end);
        return node;
    }
    public int getMaxIdx(int[] nums,int start,int end){
        if (start>end){
            return -1;
        }
        int max=nums[start];
        int maxIdx=start;
        for (int i=start+1;i<=end;i++){
            if(nums[i]>max){
                maxIdx=i;
                max=nums[i];
            }
        }
        return maxIdx;
    }
}

*655. Print Binary Tree

 struct NodePosition{
    TreeNode *node;
    int idx;

    NodePosition(TreeNode *node, int val) : node(node), idx(val) {}
};
class Solution {
public:
    vector<vector<string>> ans;
    int curr_idx;
    vector<vector<string>> printTree(TreeNode *root) {
        int height = findHeight(root);
        if (height == 0) {
            return ans;
        }
        int length=(int) pow(2,height)-1;
        ans = vector<vector<string>>(height,vector<string>(length,""));
        curr_idx=length/2;
        NodePosition* root_positioned=new NodePosition(root,curr_idx);
        queue<NodePosition*> currNodes;
        queue<NodePosition*> next;
        currNodes.push(root_positioned);
        int curr_layer=0;
        while (!currNodes.empty()){
            while(!currNodes.empty()){
                auto* point=currNodes.front();
                auto * node=point->node;
                currNodes.pop();
                ans[curr_layer][point->idx]= to_string(point->node->val);

                if (node->left){
                    next.push(new NodePosition(node->left,point->idx-(1<<(height-curr_layer-2))));
                }
                if (node->right){
                    next.push(new NodePosition(node->right,point->idx+(1<<(height-curr_layer-2))));
                }
            }
            curr_layer++;
            currNodes.swap(next);
        }
        return ans;
    }

    int findHeight(TreeNode *root) {
        if (root == nullptr) {
            return 0;
        }
        return max(findHeight(root->left), findHeight(root->right)) + 1;
    }
};

657. Robot Return to Origin

    bool judgeCircle(string moves) {
        int cache[2]={0};
        if (moves.length()%2!=0){
            return false;
        }
        for (char ch:moves) {
            switch (ch) {
                case 'L':
                    cache[0]--;
                    continue;
                case 'R':
                    cache[0]++;
                    continue;
                case 'U':
                    cache[1]--;
                    continue;
                case 'D':
                    cache[1]++;
                    continue;
            }
        }
        return cache[0]==0&&cache[1]==0;
    }

658. Find K Closest Elements

    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        if(arr.size()<=k){
            return arr;
        }
        vector<int> ans;
        int left=0;
        int right=arr.size();
        int mid=0;
        while(right-left>1){
            mid=(left+right)>>1;
            if (arr[mid]==x){
                break;
            }
            else if (arr[mid]>x){
                right=mid;
            }
            else{
                left=mid;
            }
        }
        if(arr[mid]==x){
            left=mid,right=mid+1;
        }
        while (k>0){
            if (left<0){
                right++;
                k--;
                continue;
            }
            else if(right==arr.size()){
                left--;
                k--;
                continue;
            }
            int gap_left=abs(arr[left]-x);
            int gap_right=abs(arr[right]-x);
            if(gap_left<=gap_right){
                left--;
            }
            else right++;
            k--;
        }
        //assign实现区间复制
        ans.assign(arr.begin()+left+1,arr.begin()+right);
        return ans;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值