LeedCode 思维训练(三)

1 给你一个大小为 rows x cols 的矩阵 mat,其中 mat[i][j] 是 0 或 1,请返回 矩阵 mat 中特殊位置的数目 。

特殊位置 定义:如果 mat[i][j] == 1 并且第 i 行和第 j 列中的所有其他元素均为 0(行和列的下标均 从 0 开始 ),则位置 (i, j) 被称为特殊位置。

 来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/special-positions-in-a-binary-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao.leedcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class NumSpecial {
    public static void main(String[] args) {
        int mat[][] = {{1,0,0}, {0,1,0}, {0,0,1}};
        int numSpecial = numSpecial(mat);
        System.out.println(numSpecial);
    }

    public static int numSpecial(int[][] mat) {
        List<MetaNum> metas = new ArrayList<MetaNum>();
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                int number = mat[i][j];
                if (number == 1) {
                    metas.add(new MetaNum(i, j, number));
                }
            }
        }

        List<Map.Entry<Integer, List<MetaNum>>> collect = metas
                .stream()
                .collect(Collectors.groupingBy(MetaNum::getX))
                .entrySet().stream().filter(item -> {
                    Integer key = item.getKey();
                    List<MetaNum> value = item.getValue();
                    if (value.size() == 1) {
                        return true;
                    }
                    return false;
                })
                .collect(Collectors.toList());

        Map<Integer, List<MetaNum>> metaY = metas.stream()
                .collect(Collectors.groupingBy(MetaNum::getY));

        List<Map.Entry<Integer, List<MetaNum>>> listMeta = collect
                .stream()
                .filter(item -> {
                    int y = item.getValue().get(0).getY();
                    List<MetaNum> metaNums = metaY.get(y);
                    if (metaNums.size() == 1) {
                        return true;
                    }
                    return false;
                })
                .collect(Collectors.toList());
        return listMeta.size();
    }

    static class MetaNum {
        private Integer x;
        private Integer y;
        private int val;

        public MetaNum() {

        }

        public MetaNum(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }
    }
}

2 如果数组是单调递增或单调递减的,那么它是 单调 的。

如果对于所有 i <= j,nums[i] <= nums[j],那么数组 nums 是单调递增的。 如果对于所有 i <= j,nums[i]> = nums[j],那么数组 nums 是单调递减的。

当给定的数组 nums 是单调数组时返回 true,否则返回 false。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/monotonic-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao.leedcode;

public class IsMonotonic {
    public static void main(String[] args) {
        int[] nums = {1, 2, 2, 3};
        System.out.print(isMonotonic(nums));
    }

    public static boolean isMonotonic(int[] nums) {
        boolean flag = false;
        if (nums.length <= 1) {
            return true;
        }
        for (int i = 0; i < nums.length; i++) {
            if(i+1<nums.length){
                int number=nums[i];
                int numberiplus=nums[i+1];
                if(number==numberiplus){
                    continue;
                }
                if (number > numberiplus) {
                    flag = true;
                    break;
                }
                if (number<numberiplus){
                    flag=false;
                    break;
                }
            }
        }

        for (int i = 0; i < nums.length; i++) {
            if (i + 1 < nums.length) {
                int numberi = nums[i];
                int numberiplus1 = nums[i + 1];
                if (numberi > numberiplus1 && !flag) {
                    return false;
                }
                if (numberi < numberiplus1 && flag) {
                    return false;
                }
            }
        }
        return true;
    }
}

3 给出第一个词 first 和第二个词 second,考虑在某些文本 text 中可能以 "first second third" 形式出现的情况,其中 second 紧随 first 出现,third 紧随 second 出现。

对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/occurrences-after-bigram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao.leedcode;

import java.util.ArrayList;
import java.util.List;

public class FindOcurrences {

    public static void main(String[] args) {
        String text = "alice is a good girl she is a good student";
        String first = "a";
        String second = "good";

        String[] ocurrences = findOcurrences(text, first, second);
        for (int i = 0; i < ocurrences.length; i++) {
            System.out.print(ocurrences[i]);
        }

    }

    public static String[] findOcurrences(String text, String first, String second) {
        String[] stris = text.split(" ");
        List<String> str = new ArrayList<>();
        for (int i = 0; i < stris.length; i++) {
            if (i + 2 < stris.length) {
                String firs = stris[i];
                if (firs.equals(first)) {
                    String secon = stris[i + 1];
                    if (secon.equals(second)) {
                        str.add(stris[i + 2]);
                    }
                }
            }
        }
        String[] sti = new String[str.size()];
        for (int i = 0; i < str.size(); i++) {
            sti[i] = str.get(i);
        }
        return sti;
    }
}

4 对于字符串 s 和 t,只有在 s = t + ... + t(t 自身连接 1 次或多次)时,我们才认定 “t 能除尽 s”。

给定两个字符串 str1 和 str2 。返回 最长字符串 x,要求满足 x 能除尽 str1 且 X 能除尽 str2 。

示例 1:

输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"
示例 2:

输入:str1 = "ABABAB", str2 = "ABAB"
输出:"AB"
示例 3:

输入:str1 = "LEET", str2 = "CODE"
输出:""

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/greatest-common-divisor-of-strings 
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao.leedcode;


import java.util.HashSet;
import java.util.Set;

public class GcdOfStrings {
    public static void main(String[] args) {
        String str1 = "CXTXNCXTXNCXTXNCXTXNCXTXN";
        String str2 = "CXTXNCXTXNCXTXNCXTXNCXTXNCXTXNCXTXNCXTXNCXTXNCXTXNCXTXNCXTXNCXTXN";
        System.out.println(gcdOfStrings(str1, str2));
    }

    public static String gcdOfStrings(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        int start = Math.min(len1, len2);
        for (int i = start; i > 0; i--) {
            if (len1 % i == 0 && len2 % i == 0) {
                String sub = str1.substring(0, i);
                if(checkSub(sub,str1) && checkSub(sub,str2)){
                    return sub;
                }
            }
        }
        return "";
    }

    private static boolean checkSub(String sub, String oristr) {
        int len = oristr.length() / sub.length();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            stringBuilder.append(sub);
        }
        return stringBuilder.toString().equals(oristr);
    }
}

5 一个整数 num 的 k 美丽值定义为 num 中符合以下条件的 子字符串 数目:

子字符串长度为 k 。
子字符串能整除 num 。
给你整数 num 和 k ,请你返回 num 的 k 美丽值。

注意:

允许有 前缀 0 。
0 不能整除任何值。
一个 子字符串 是一个字符串里的连续一段字符序列。

示例 1:

输入:num = 240, k = 2
输出:2
解释:以下是 num 里长度为 k 的子字符串:
- "240" 中的 "24" :24 能整除 240 。
- "240" 中的 "40" :40 能整除 240 。
所以,k 美丽值为 2 。
示例 2:

输入:num = 430043, k = 2
输出:2
解释:以下是 num 里长度为 k 的子字符串:
- "430043" 中的 "43" :43 能整除 430043 。
- "430043" 中的 "30" :30 不能整除 430043 。
- "430043" 中的 "00" :0 不能整除 430043 。
- "430043" 中的 "04" :4 不能整除 430043 。
- "430043" 中的 "43" :43 能整除 430043 。
所以,k 美丽值为 2 。


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-k-beauty-of-a-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao.leedcode;

public class DivisorSubstrings {
    public static void main(String[] args) {
        int num = 240;
        int k = 2;
        System.out.println(divisorSubstrings(num, k));
    }

    public static int divisorSubstrings(int num, int k) {
        int result = 0;
        String numstr = String.valueOf(num);
        for (int i = 0; i < numstr.length(); i++) {
            if (i + k <= numstr.length()) {
                String nums = numstr.substring(i, i + k);
                int parseInteget = Integer.parseInt(nums);
                if (parseInteget == 0) {
                    continue;
                }
                if (num % parseInteget != 0) {
                    continue;
                }
                result++;
            }
        }
        return result;
    }
}

6 设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。

示例:

输入: arr = [1,3,5,7,2,4,6,8], k = 4
输出: [1,2,3,4]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/smallest-k-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao.leedcode;

import com.alibaba.fastjson.JSONObject;

import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class SmallestK {
    public static void main(String[] args) {
        int arr[] = {1, 3, 5, 7, 2, 4, 6, 8};
        int k = 4;
        System.out.println(JSONObject.toJSONString(smallestK(arr, k)));
    }


    public static int[] smallestK(int[] arr, int k) {
        if (k <= 0) {return new int[]{};}
        Queue<Integer> queue = new PriorityQueue<>((num1, num2) -> num2-num1);
        for (int i = 0; i < arr.length; i++) {
            Integer peek = queue.peek();
            int number = arr[i];
            if(queue.isEmpty() || queue.size() < k){
                queue.add(number);
                continue;
            }
            if (number < peek && queue.size() >= k) {
                queue.poll();
                queue.add(number);
            }
        }
        int[] result = new int[queue.size()];
        int index = 0;
        for (Iterator<Integer> iterator = queue.iterator(); iterator.hasNext(); ) {
            Integer next = iterator.next();
            result[index] = next;
            index++;
        }
        return result;
    }
}

7 给你一个数组 candies 和一个整数 extraCandies ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目。

对每一个孩子,检查是否存在一种方案,将额外的 extraCandies 个糖果分配给孩子们之后,此孩子有 最多 的糖果。注意,允许有多个孩子同时拥有 最多 的糖果数目。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/kids-with-the-greatest-number-of-candies
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处

 

package worn.xiao.leedcode;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class KidsWithCandies {

    public static void main(String[] args) {
        int[] candies={2,3,5,1,3};
        int extraCandies = 3;
       System.out.println(JSONObject.toJSONString(kidsWithCandies(candies,extraCandies)));
    }

    public static List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
        int max = 0;
        for (int i = 0; i < candies.length; i++) {
            int number = candies[i];
            if (number > max) {
                max = number;
            }
        }
        int finalMax = max;
        return Arrays.stream(candies)
                .mapToObj(item -> {
                    int maxrel = item + extraCandies;
                    return finalMax - maxrel <= 0;
                }).collect(Collectors.toList());
    }
}

8    给你一个整数数组 arr 和两个整数 k 和 threshold 。请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。

package worn.xiao.leedcode;

public class NumOfSubarrays {
    public static void main(String[] args) {
        int arr[] = {2, 2, 2, 2, 5, 5, 5, 8};
        int k = 3;
        int threshold = 4;
        System.out.println(numOfSubarrays(arr, k, threshold));
    }

    public static int numOfSubarrays(int[] arr, int k, int threshold) {
        if (threshold == 0) {
            return arr.length - k + 1;
        }
        int result = 0;
        for (int i = 0; i < arr.length; i++) {
            int sum = 0;
            int numlen = i + k;
            for (int j = i; j < numlen && numlen <= arr.length; j++) {
                sum += arr[j];
            }
            int number = sum / k;
            if (number < threshold) {
                continue;
            }
            result++;
        }
        return result;
    }
}

9 给你两个数 hour 和 minutes 。请你返回在时钟上,由给定时间的时针和分针组成的较小角的角度(60 单位制)。

package worn.xiao.leedcode;

public class AngleClock {
    public static void main(String[] args) {
        int hour=1;
        int minutes=57;
        System.out.println(angleClock(hour,minutes));
    }

    public static double angleClock(int hour, int minutes) {
        double number = (hour % 12 * 5) + 5 * (minutes / 60.0);
        double num = Math.abs(minutes - number);
        return Math.min(360 * (num / 60),360-( 360 * (num / 60)));
    }
}

10  给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

package worn.xiao.leedcode;

public class Transpose {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] transpose = transpose(matrix);
        printMatrix(transpose);
    }

    private static void printMatrix(int[][] transpose) {
        for (int i = 0; i < transpose.length; i++) {
            for (int j = 0; j < transpose[i].length; j++) {
                System.out.print(transpose[i][j]);
            }
            System.out.println();
        }
    }

    public static int[][] transpose(int[][] matrix) {
        int row = matrix.length;
        int colume = matrix[0].length;
        int[][] newMatrix = new int[colume][row];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (i == j) {
                    newMatrix[i][j] = matrix[i][j];
                    continue;
                }
                newMatrix[j][i] = matrix[i][j];
            }
        }
        return newMatrix;
    }
}

11 小镇里有 n 个人,按从 1 到 n 的顺序编号。传言称,这些人中有一个暗地里是小镇法官。

如果小镇法官真的存在,那么:

小镇法官不会信任任何人。
每个人(除了小镇法官)都信任这位小镇法官。
只有一个人同时满足属性 1 和属性 2 。
给你一个数组 trust ,其中 trust[i] = [ai, bi] 表示编号为 ai 的人信任编号为 bi 的人。

如果小镇法官存在并且可以确定他的身份,请返回该法官的编号;否则,返回 -1 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-town-judge (未完成
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao.leedcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class FindJudge {
    public static void main(String[] args) {
        //[[1,3],[1,4],[2,3],[2,4],[4,3]]
        int[][] trust = {{1,3},{1,4},{2,3},{2,4},{4,3}};
        int n = 4;
        System.out.println(findJudge(n, trust));
    }

    public static int findJudge(int n, int[][] trust) {
        //创建信任
        Map<Integer, Set<Integer>> integerMap = new HashMap<>();
        for (int i = 0; i < trust.length; i++) {
            int[] valPair = trust[i];
            int key = valPair[0];
            int val = valPair[1];

            Set<Integer> valSet = integerMap.get(val);
            if (valSet==null) {
                HashSet<Integer> hashSet = new HashSet<>();
                hashSet.add(key);
                integerMap.put(val, hashSet);
                continue;
            }
            if (valSet.contains(key)) {
                continue;
            }
            valSet.add(key);
        }
        if (integerMap.size() > 1) {
            return -1;
        }
        return integerMap.keySet().iterator().next();
    }
}

12 实现一个 MyCalendar 类来存放你的日程安排。如果要添加的日程安排不会造成 重复预订 ,则可以存储这个新的日程安排。

 当两个日程安排有一些时间上的交叉时(例如两个日程安排都在同一时间内),就会产生 重复预订 。

 日程可以用一对整数 start 和 end 表示,这里的时间是半开区间,即 [start, end), 实数 x 的范围为,  start <= x < end 。

实现 MyCalendar 类:

MyCalendar() 初始化日历对象。
boolean book(int start, int end) 如果可以将日程安排成功添加到日历中而不会导致重复预订,返回 true 。否则,返回 false 并且不要将该日程安排添加到日历中。


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/my-calendar-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

package worn.xiao;

import java.util.ArrayList;
import java.util.List;

public class MyCalendar {
    private List<Node> nodes = new ArrayList<>();

    public MyCalendar() {

    }

    public boolean book(int start, int end) {
        boolean result = true;
        for (int i = 0; i < nodes.size(); i++) {
            Node node = nodes.get(i);
            int x = node.x;
            int y = node.y;
            //有交集
            if (start >= x && start < y) {
                return false;
            }
            if (end > x && end < y) {
                return false;
            }
            if (start <= x && end >= y) {
                return false;
            }
        }
        return result;
    }

    public void addNodes(Node node) {
        if (!book(node.x, node.y)) {
            return;
        }
        nodes.add(node);
    }

    static class Node {
        private int x = 0;
        private int y = 0;

        public Node(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}

13   给你一个 m * n 的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。幸运数 是指矩阵中满足同时下列两个条件的元素:

在同一行的所有元素中最小
在同一列的所有元素中最大

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/lucky-numbers-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao;

import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class LuckyNumbers {
    public static void main(String[] args) {
        int[][] matrix = {{3, 7, 8}, {9, 11, 13}, {15, 16, 17}};
        List<Integer> luckyNumbers = luckyNumbers(matrix);
        for (int i = 0; i < luckyNumbers.size(); i++) {
            System.out.println(luckyNumbers.get(i));
        }
    }

    public static List<Integer> luckyNumbers(int[][] matrix) {
        List<Node> nodeList = new ArrayList<>();
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                int val = matrix[i][j];
                nodeList.add(new Node(i, j, val));
            }
        }
        //rowMap
        Map<Integer, Node> rowMap = getRowMap(nodeList);
        //columnMap
        Map<Integer, Node> columnMap = getColumnMap(nodeList);
        return rowMap
                .values()
                .stream()
                .map(node -> {
                    int y = node.getY();
                    Node nod = columnMap.get(y);
                    if (nod != null && node.getVal() == nod.getVal()) {
                        return nod.getVal();
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private static Map<Integer, Node> getColumnMap(List<Node> nodeList) {
        return nodeList
                .stream()
                .collect(Collectors.groupingBy(Node::getY))
                .entrySet()
                .stream()
                .map(item -> {
                    Integer key = item.getKey();
                    List<Node> collects = item
                            .getValue()
                            .stream()
                            .sorted(new Comparator<Node>() {
                                @Override
                                public int compare(Node o1, Node o2) {
                                    return o2.getVal() - o1.getVal();
                                }
                            })
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collects)) {
                        return new KeyValPair(key, collects.get(0));
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(KeyValPair::getIndex,
                        KeyValPair::getNode));
    }

    public static Map<Integer, Node> getRowMap(List<Node> nodeList) {
        return nodeList
                .stream()
                .collect(Collectors.groupingBy(Node::getX))
                .entrySet()
                .stream()
                .map(item -> {
                    Integer key = item.getKey();
                    List<Node> nodes = item
                            .getValue()
                            .stream()
                            .sorted(Comparator.comparingInt(Node::getVal))
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(nodes)) {
                        return new KeyValPair(key, nodes.get(0));
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(KeyValPair::getIndex,
                        KeyValPair::getNode));
    }

    static class KeyValPair {
        private int index;
        private Node node;

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public Node getNode() {
            return node;
        }

        public void setNode(Node node) {
            this.node = node;
        }

        public KeyValPair() {
        }

        public KeyValPair(int index, Node node) {
            this.index = index;
            this.node = node;
        }
    }

    static class Node {
        private int x;
        private int y;
        private int val;

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public Node() {
        }

        public Node(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }

    }
}

14  给你两个 m x n 的二进制矩阵 grid1 和 grid2 ,它们只包含 0 (表示水域)和 1 (表示陆地)。一个 岛屿 是由 四个方向 (水平或者竖直)上相邻的 1 组成的区域。任何矩阵以外的区域都视为水域。

如果 grid2 的一个岛屿,被 grid1 的一个岛屿 完全 包含,也就是说 grid2 中该岛屿的每一个格子都被 grid1 中同一个岛屿完全包含,那么我们称 grid2 中的这个岛屿为 子岛屿 。

请你返回 grid2 中 子岛屿 的 数目 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-sub-islands (超时)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

package worn.xiao;

import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class CountSubIslands {
    public static void main(String[] args) {
        int[][] grid1 = {{1, 0, 1, 0, 1}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}, {1, 1, 1, 1, 1}, {1, 0, 1, 0, 1}};
        int[][] grid2 = {{1,1,1,0,0}, {0,0,1,1,1}, {0,1,0,0,0}, {1,0,1,1,0}, {0,1,0,1,0}};
        System.out.println(countSubIslands(grid1, grid2));
    }

    public static int countSubIslands(int[][] grid1, int[][] grid2) {
        List<List<Point>> points = getPoints(grid2);
        if (points.isEmpty()) {
            return 0;
        }
        return points.stream()
                .map(item -> {
                    List<Point> items = item
                            .stream()
                            .filter(ele -> {
                                if (grid1[ele.x][ele.y] == 0) {
                                    return true;
                                }
                                return false;
                            })
                            .collect(Collectors.toList());
                    if (items.isEmpty()) {
                        return 1;
                    }
                    return 0;
                })
                .mapToInt(Integer::valueOf).sum();
    }

    public static List<List<Point>> getPoints(int[][] grid) {
        List<List<Point>> result = new ArrayList<>();
        Set<Point> visited = new HashSet<>();


        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                Point point = new Point(i, j, grid[i][j]);
                if (visited.contains(point)) {
                    continue;
                }
                int number = grid[i][j];
                if (number == 0) {
                    visited.add(point);
                    continue;
                }
                List<Point> points = new ArrayList<>();
                Deque<Point> pointDeque = new LinkedList<>();
                pointDeque.push(point);
                while (!pointDeque.isEmpty()) {
                    Point pop = pointDeque.pop();
                    if (visited.contains(pop)) {
                        continue;
                    }
                    visited.add(pop);
                    int x = pop.x;
                    int y = pop.y;
                    if(isInBound(x,y,grid)){
                        points.add(pop);
                    }
                    //上
                    if (isInBound(x, y + 1, grid) && grid[x][y + 1] == 1) {
                        Point point1 = new Point(x, y + 1, grid[x][y + 1]);
                        if (!visited.contains(point1)) {
                            pointDeque.push(point1);
                        }
                    }
                    //下
                    if (isInBound(x, y - 1, grid) && grid[x][y - 1] == 1) {
                        Point point2 = new Point(x, y - 1, grid[x][y - 1]);
                        if (!visited.contains(point2)) {
                            pointDeque.push(point2);
                        }
                    }
                    //左
                    if (isInBound(x - 1, y, grid) && grid[x - 1][y] == 1) {
                        Point point3 = new Point(x - 1, y, grid[x - 1][y]);
                        if (!visited.contains(point3)) {
                            pointDeque.push(point3);
                        }
                    }
                    //右
                    if (isInBound(x + 1, y, grid) && grid[x + 1][y] == 1) {
                        Point point4 = new Point(x + 1, y, grid[x + 1][y]);
                        if (!visited.contains(point4)) {
                            pointDeque.push(point4);
                        }
                    }
                }
                result.add(points);
            }
        }
        return result;
    }

    /**
     * 在函数范围边界内
     *
     * @param x
     * @param y
     * @return
     */
    private static boolean isInBound(int x, int y, int[][] grid) {
        if (x < 0 || x >= grid.length) {
            return false;
        }
        if (y < 0 || y >= grid[0].length) {
            return false;
        }
        return true;
    }

    static class Point {
        private int x;
        private int y;
        private int val;

        @Override
        public int hashCode() {
            return x + y + val;
        }

        @Override
        public boolean equals(Object obj) {
            Point point = (Point) obj;
            return this.x == point.x && this.y == point.y && this.val == point.val;
        }

        public Point() {

        }

        public Point(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }

    }
}

15 给你一个正方形矩阵 mat,请你返回矩阵对角线元素的和。请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和。

package worn.xiao;

public class DiagonalSum {
    public static void main(String[] args) {
        int[][] mat = {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}};
        System.out.println(diagonalSum(mat));
    }

    public static int diagonalSum(int[][] mat) {
        int row = mat.length - 1;
        int middle = (int) Math.floor(row / 2);
        int num = mat[middle][middle];
        int sum0 = 0;
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                if (i == j) {
                    sum0 += mat[i][j];
                    int number = mat[(mat.length - 1) - i][j];
                    sum0 += number;
                }
            }
        }
        if (mat.length % 2 == 0) {
            return sum0;
        }
        return sum0 - num;
    }
}

16 设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。

请实现 KthLargest 类:

KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/kth-largest-element-in-a-stream
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao;

import java.util.Comparator;
import java.util.PriorityQueue;

public class KthLargest {
    private int k;
    private int[] nums;
    private PriorityQueue<Integer> maxQueue = new PriorityQueue<>();

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.nums = nums;

        for (int i = 0; i < nums.length; i++) {
            if (maxQueue.size() >=k) {
                Integer peek = maxQueue.peek();
                if (peek < nums[i]) {
                    maxQueue.poll();
                    maxQueue.add(nums[i]);
                }
                continue;
            }
            maxQueue.add(nums[i]);
        }
    }

    public int add(int val) {
        if (maxQueue.size() < k) {
            maxQueue.add(val);
            return getLast(maxQueue);
        }
        Integer peek = maxQueue.peek();
        if (peek < val) {
            maxQueue.poll();
            maxQueue.add(val);
        }
        return getLast(maxQueue);
    }

    private int getLast(PriorityQueue<Integer> maxQueue) {
        Integer[] ques = new Integer[maxQueue.size()];
        maxQueue.toArray(ques);
        return ques[0];
    }

    public static void main(String[] args) {
        int k = 3;
        int[] nums = {4, 5, 8, 2};
        KthLargest obj = new KthLargest(k, nums);
        System.out.println(obj.add(3));
        System.out.println(obj.add(5));
        System.out.println(obj.add(10));
        System.out.println(obj.add(9));
        System.out.println(obj.add(4));
    }
}

17 给你一个 n x n 的 方形 整数数组 matrix ,请你找出并返回通过 matrix 的下降路径 的 最小和 。

下降路径 可以从第一行中的任何元素开始,并从每一行中选择一个元素。在下一行选择的元素和当前行所选元素最多相隔一列(即位于正下方或者沿对角线向左或者向右的第一个元素)。具体来说,位置 (row, col) 的下一个元素应当是 (row + 1, col - 1)、(row + 1, col) 或者 (row + 1, col + 1) 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-falling-path-sum (超时)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

package worn.xiao;

import java.util.*;

public class MinFallingPathSum {

    public static void main(String[] args) {
        //[[100,-42,-46,-41],[31,97,10,-10],[-58,-51,82,89],[51,81,69,-51]]
        int[][] matrix = {{100,-42,-46,-41}, {31,97,10,-10}, {-58,-51,82,89},{51,81,69,-51}};
        System.out.println(minFallingPathSum(matrix));
    }

    public static int minFallingPathSum(int[][] matrix) {
        int minSum = Integer.MAX_VALUE;
        for (int j = 0; j < matrix.length; j++) {
            int number = getNextRowMinPoin(new Point(0, j, matrix[0][j]),matrix);
            if (minSum > number) {
                minSum = number;
            }
        }
        return minSum;
    }
    
    private static int getNextRowMinPoin(Point peek, int[][] matrix) {
        int result = Integer.MAX_VALUE;
        int x = peek.x;
        int y = peek.y;
        if (x >= matrix.length - 1) {
            return peek.val;
        }
        if (inBound(x + 1, y - 1, matrix)) {
            int rightNumber = peek.val + getNextRowMinPoin(new Point(x + 1, y - 1, matrix[x + 1][y - 1]), matrix);
            if (result > rightNumber) {
                result = rightNumber;
            }
        }
        if (inBound(x + 1, y, matrix)) {
            int middNumber = peek.val + getNextRowMinPoin(new Point(x + 1, y, matrix[x + 1][y]), matrix);
            if (result > middNumber) {
                result = middNumber;
            }
        }
        if (inBound(x + 1, y + 1, matrix)) {
            int leftNumber = peek.val + getNextRowMinPoin(new Point(x + 1, y + 1, matrix[x + 1][y + 1]), matrix);
            if (result > leftNumber) {
                result = leftNumber;
            }
        }
        return result;
    }
    
    private static boolean inBound(int x, int y, int[][] matrix) {
        if (x < 0 || x >= matrix.length) {
            return false;
        }
        if (y < 0 || y >= matrix.length) {
            return false;
        }
        return true;
    }

    static class Point {
        private int x;
        private int y;
        private int val;

        public Point(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }
    }
}

18 设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于已构建的神奇字典中。

实现 MagicDictionary 类:

MagicDictionary() 初始化对象
void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/US1pGT
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

package worn.xiao;

public class MagicDictionary {

    private String[] dictionary;

    public MagicDictionary() {

    }

    public void buildDict(String[] dictionary) {
        this.dictionary = dictionary;
    }

    public boolean search(String searchWord) {
        boolean search = false;
        for (int i = 0; i < dictionary.length; i++) {
            String s = dictionary[i];
            char[] chars = s.toCharArray();
            char[] newchars = searchWord.toCharArray();
            if (chars.length != newchars.length) {
                continue;
            }
            int length = chars.length;
            int number = 0;
            for (int j = 0; j < chars.length; j++) {
                char oc = chars[j];
                char nc = searchWord.charAt(j);
                if (oc == nc) {
                    number++;
                }
            }
            if (length - 1 != number) {
                continue;
            }
            search = true;
        }
        return search;
    }
}

19 给你一个下标从 0 开始的字符串 s ,以及一个下标从 0 开始的整数数组 spaces 。

数组 spaces 描述原字符串中需要添加空格的下标。每个空格都应该插入到给定索引处的字符值 之前 。

例如,s = "EnjoyYourCoffee" 且 spaces = [5, 9] ,那么我们需要在 'Y' 和 'C' 之前添加空格,这两个字符分别位于下标 5 和下标 9 。因此,最终得到 "Enjoy Your Coffee" 。
请你添加空格,并返回修改后的字符串。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/adding-spaces-to-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

package worn.xiao;

public class AddSpaces {


    public static void main(String[] args) {
        String s="LeetcodeHelpsMeLearn";
        int[] spaces={8,13,15};
        System.out.println(addSpaces(s,spaces));
    }

    public static String addSpaces(String s, int[] spaces) {
        char[] chars = s.toCharArray();
        int spaceIndex=0;
        StringBuilder stringBuilder=new StringBuilder();
        for(int i=0;i<chars.length;i++){
           Character character = chars[i];
           if(spaceIndex>=spaces.length){
               stringBuilder.append(character);
               continue;
           }
           if(i!=spaces[spaceIndex]){
               stringBuilder.append(character);
               continue;
           }
           stringBuilder.append(" ");
           stringBuilder.append(character);
           spaceIndex++;
        }
        return stringBuilder.toString();
    }
}

20 给你一个下标从 0 开始的字符串数组 words 和两个整数:left 和 right 。

如果字符串以元音字母开头并以元音字母结尾,那么该字符串就是一个 元音字符串 ,其中元音字母是 'a'、'e'、'i'、'o'、'u' 。

返回 words[i] 是元音字符串的数目,其中 i 在闭区间 [left, right] 内。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-the-number-of-vowel-strings-in-range
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

package worn.xiao;

import java.util.Arrays;
import java.util.List;

public class VowelStrings {

    public static void main(String[] args) {
        String[] words = {"are", "amy", "u"};
        int left = 0;
        int right = 2;
        System.out.println(vowelStrings(words, left, right));
    }

    public static int vowelStrings(String[] words, int left, int right) {
        int sum = 0;
        for (int i = left; i <= right; i++) {
            String word = words[i];
            if (checkIsYuyin(word)) {
                sum++;
            }
        }
        return sum;
    }

    private static boolean checkIsYuyin(String word) {
        char firstChar = word.charAt(0);
        char lastChar = word.charAt(word.length() - 1);
        Character[] characters = {'a', 'e', 'i', 'o', 'u'};
        List<Character> characterList = Arrays.asList(characters);
        if (!characterList.contains(firstChar)) {
            return false;
        }
        if (!characterList.contains(lastChar)) {
            return false;
        }
        return true;
    }
}

21 给你个整数数组 arr,其中每个元素都 不相同。

请你找到所有具有最小绝对差的元素对,并且按升序的顺序返回。

每对元素对 [a,b] 如下:

a , b 均为数组 arr 中的元素
a < b
b - a 等于 arr 中任意两个元素的最小绝对差


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-absolute-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import com.alibaba.fastjson.JSONObject;

import java.util.*;
import java.util.stream.Collectors;

public class MinimumAbsDifference {


    public static void main(String[] args) {
        int arr[]= {4,2,1,3};
        List<List<Integer>> lists = minimumAbsDifference(arr);
        System.out.println(JSONObject.toJSONString(lists));
    }

    public static List<List<Integer>> minimumAbsDifference(int[] arr) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> arrays = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            arrays.add(arr[i]);
        }
        List<Integer> newArrays = arrays.stream()
                .sorted(Comparator.comparingInt(o -> o))
                .collect(Collectors.toList());

        int min = Integer.MAX_VALUE;
        int index = 0;
        for (int i = 0; i < newArrays.size(); i++) {
            Integer numberOne = newArrays.get(i);
            if (i + 1 >= newArrays.size()) {
                continue;
            }
            Integer numberTwo = newArrays.get(i + 1);
            int abs = Math.abs((numberTwo - numberOne));
            if (min > abs) {
                min = abs;
                index = i;
            }
        }
        for (int i = index; i < newArrays.size(); i++) {
            Integer numone = newArrays.get(i);
            if (i + 1 >= newArrays.size()) {
                continue;
            }
            Integer numTwo = newArrays.get(i + 1);
            int abs = Math.abs((numTwo - numone));
            if (min != abs) {
                continue;
            }
            result.add(Arrays.asList(numone, numTwo));
        }
        return result;
    }

}

22 给你一个整数数组 arr ,请你将数组中的每个元素替换为它们排序后的序号。

序号代表了一个元素有多大。序号编号的规则如下:

序号从 1 开始编号。
一个元素越大,那么序号越大。如果两个元素相等,那么它们的序号相同。
每个数字的序号都应该尽可能地小。


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rank-transform-of-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ArrayRankTransform {
    public static void main(String[] args) {
        //[37,12,28,9,100,56,80,5,12]
        int[] arr = {37,12,28,9,100,56,80,5,12};
        int[] ints = arrayRankTransform(arr);
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }
    }


    public static int[] arrayRankTransform(int[] arr) {
        List<Integer> arrays = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            arrays.add(arr[i]);
        }
        List<Integer> arrayRankTransform = arrays
        .parallelStream()
        .collect(Collectors.groupingBy(item -> item))
        .keySet()
        .parallelStream()
        .sorted(Comparator.comparingInt(o -> o))
        .collect(Collectors.toList());

        int[] resutl = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            int number = arr[i];
            int numberIndex = arrayRankTransform.indexOf(number);
            resutl[i] = numberIndex + 1;
        }
        return resutl;
    }
}

 23 只有满足下面几点之一,括号字符串才是有效的:

它是一个空字符串,或者 它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
它可以被写作 (A),其中 A 是有效字符串。给定一个括号字符串 s ,在每一次操作中,你都可以在字符串的任何位置插入一个括号

例如,如果 s = "()))" ,你可以插入一个开始括号为 "(()))" 或结束括号为 "())))" 。
返回 为使结果字符串 s 有效而必须添加的最少括号数。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-add-to-make-parentheses-valid
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Deque;
import java.util.LinkedList;

public class MinAddToMakeValid {


    public static void main(String[] args) {
        String str = "()))((";
        System.out.println(minAddToMakeValid(str));
    }

    public static int minAddToMakeValid(String s) {
        if (s.length() == 0) {
            return 0;
        }
        char[] chars = s.toCharArray();

        Deque<Character> leftRange = new LinkedList<>();
        Deque<Character> rightRange = new LinkedList<>();
        for (int i = 0; i < chars.length; i++) {
            char chr = chars[i];
            if (chr == '(') {
                leftRange.push(chr);
                continue;
            }
            if (chr == ')') {
                rightRange.push(chr);
                Character peek = leftRange.peek();
                if(peek!=null && peek=='('){
                    leftRange.pop();
                    rightRange.pop();
                }
            }
        }
        return leftRange.size()+rightRange.size();
    }
}

24  给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。

整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3x

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/power-of-three
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

class Solution {
    public boolean isPowerOfThree(int n) {
        if(n==0){
          return false;
        }
        while (n % 3 == 0) {
            n = n / 3;
        }
        if (n == 1) {
            return true;
        }
        return false;
    }
}

25 给你一个下标从 0 开始的整数数组 nums 和两个整数 key 和 k 。K 近邻下标 是 nums 中的一个下标 i ,并满足至少存在一个下标 j 使得 |i - j| <= k 且 nums[j] == key 。

以列表形式返回按 递增顺序 排序的所有 K 近邻下标。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-all-k-distant-indices-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class FindKDistantIndices {

    public static void main(String[] args) {
        int[] nums = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
        int key = 1;
        int k = 1000;
        System.out.println(JSONObject.toJSONString(findKDistantIndices(nums, key, k)));
    }


    /**
     * 1 收集索引
     * 2 遍历数组对每个索引做邻近下标的判断
     * 3 对收集的邻近下标排序
     *
     * @param nums
     * @param key
     * @param k
     * @return
     */
    public static List<Integer> findKDistantIndices(int[] nums, int key, int k) {
        List<Integer> indexs = new ArrayList<>();
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == key) {
                indexs.add(i);
            }
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < indexs.size(); j++) {
                int numberi = indexs.get(j);
                boolean isTrue = Math.abs((i - numberi)) <= k && nums[numberi] == key;
                if (isTrue && !result.contains(i)) {
                    result.add(i);
                }
            }
        }
        return result.stream()
                .sorted(Comparator.comparingInt(o -> o))
                .collect(Collectors.toList());
    }
}

26 给你一个正整数 n ,请你计算在 [1,n] 范围内能被 357 整除的所有整数之和。

返回一个整数,用于表示给定范围内所有满足约束条件的数字之和。

 

  

import java.util.ArrayList;
import java.util.List;

public class SumOfMultiples {
    public static void main(String[] args) {
        int n=7;
        System.out.println(sumOfMultiples(7));
    }

    public static int sumOfMultiples(int n) {
        List<Integer> numbers = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            if(i%3==0 || i%5==0 || i%7==0){
                numbers.add(i);
            }
        }
        if(numbers.size()==0){
            return 0;
        }
        return numbers
                .stream()
                .mapToInt(item->item)
                .sum();
    }
}

27 给你一个长度为 n 的整数数组 nums ,请你求出每个长度为 k 的子数组的 美丽值 。

一个子数组的 美丽值 定义为:如果子数组中第 x 小整数 是 负数 ,那么美丽值为第 x 小的数,否则美丽值为 0 。

请你返回一个包含 n - k + 1 个整数的数组,依次 表示数组中从第一个下标开始,每个长度为 k 的子数组的 美丽值 。

子数组指的是数组中一段连续 非空 的元素序列。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sliding-subarray-beauty
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class GetSubarrayBeauty {
    //[-3,1,2,-3,0,-3]
    //2
    //1
    public static void main(String[] args) {
        int[] nums = {-3,1,2,-3,0,-3};
        int k = 2;
        int x = 1;
        int[] subarrayBeauty = getSubarrayBeauty(nums, k, x);
        System.out.println(JSONObject.toJSONString(subarrayBeauty));
    }


    /**
     * 1 得到子数组
     * 2 遍历子数组 求出每个数组的美丽值
     * 3 返回美丽值数组
     *
     * @param nums
     * @param k
     * @param x
     * @return
     */
    public static int[] getSubarrayBeauty(int[] nums, int k, int x) {
        List<List<Integer>> allSubArr = getAllSubArray(nums, k);
        List<Integer> result = new ArrayList<>();
        for (List<Integer> subArr : allSubArr) {
            result.add(getMelizhi(subArr, x));
        }
        int[] arr = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            arr[i] = result.get(i);
        }
        return arr;
    }

    public static Integer getMelizhi(List<Integer> subArr, int x) {
        PriorityQueue<Integer> deque =  new PriorityQueue<Integer>((o1, o2) -> o2-o1);

        for (int i = 0; i < subArr.size(); i++) {
            Integer newNum = subArr.get(i);
            Integer peek = deque.peek();
            if (deque.size() < x) {
                deque.add(newNum);
                continue;
            }
            if( peek > newNum && deque.size() >= x){
                deque.poll();
                deque.add(newNum);
            }
        }
        Integer peek = deque.peek();
        if (peek < 0) {
            return peek;
        }
        return 0;
    }

    public static List<List<Integer>> getAllSubArray(int[] nums, int k) {
        List<List<Integer>> allSubArr = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            List<Integer> subArr = new ArrayList<>();
            int rightBound = i + k;
            for (int j = i; j < rightBound && rightBound <= nums.length; j++) {
                subArr.add(nums[j]);
            }
            if (subArr.size() == k) {
                allSubArr.add(subArr);
            }
        }
        return allSubArr;
    }
}

28  在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:

值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。

返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rotting-oranges 
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class OrangesRotting {

    public static void main(String[] args) {
        //[[1,2]]
        int[][] grid={{1,2}};
        System.out.println(orangesRotting(grid));
    }

    /**
     * 橙子
     * 1 统计橘子个数 并把腐烂的橘子先压入栈中
     * 2 出栈直到栈为空检测四周不腐烂的橘子 放入队列 并标记为腐烂 分钟数+1 统计腐烂橘子数
     * 3 把队列中的腐烂橘子出队列依次找到周围好的橘子压入栈中
     * 4 栈和队列都为空 跳出循环 否则 重复步揍 2
     * 5 对比橘子总个数和腐烂橘子数 如果相等返回分钟数 如果不等返回-1
     *
     * @param grid
     * @return
     */
    public static int orangesRotting(int[][] grid) {
        Deque<Point> stack = new LinkedList<>();
        Queue<Point> pointQueue = new LinkedList<>();
        int totalNumber = getTotalNumber(grid, stack);
        int minute = 0;
        int unRightOrange = stack.size();

        while (!stack.isEmpty()) {
            while (!stack.isEmpty()) {
                Point pop = stack.pop();
                inRightOrangeQueue(pop, pointQueue, grid, unRightOrange);
            }
            if(!pointQueue.isEmpty()){
                unRightOrange+=pointQueue.size();
                minute++;
            }
            while (!pointQueue.isEmpty()) {
                Point poll = pointQueue.poll();
                stack.push(poll);
            }
        }
        if (unRightOrange == totalNumber) {
            return minute;
        }
        return -1;
    }

    /**
     * 检测四周好的橘子入队列
     *
     * @param pop
     * @param grid
     */
    private static void inRightOrangeQueue(Point pop, Queue<Point> pointQueue, int[][] grid, int unRightOrange) {
        int x = pop.x;
        int y = pop.y;
        if (checkInGrid(x, y+1, grid) && grid[x][y+1] == 1) {//右
            pointQueue.add(new Point(x, y+1, 2));
            grid[x][y+1] = 2;
            unRightOrange++;
        }
        if (checkInGrid(x, y-1, grid) && grid[x][y-1] == 1) {//左
            pointQueue.add(new Point(x, y-1, 2));
            grid[x][y-1] = 2;
            unRightOrange++;
        }
        if (checkInGrid(x-1, y, grid) && grid[x-1][y] == 1) {//上
            pointQueue.add(new Point(x-1, y , 2));
            grid[x-1][y] = 2;
            unRightOrange++;
        }
        if (checkInGrid(x+1, y, grid) && grid[x+1][y] == 1) {//下
            pointQueue.add(new Point(x+1, y, 2));
            grid[x+1][y] = 2;
            unRightOrange++;
        }
    }

    //检测是否在表格内
    private static boolean checkInGrid(int x, int y, int[][] grid) {
        if (x < 0 || x >= grid.length) {
            return false;
        }
        if (y < 0 || y >= grid[0].length) {
            return false;
        }
        return true;
    }

    public static int getTotalNumber(int[][] grid, Deque<Point> stack) {
        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                int number = grid[i][j];
                if (number == 1) {
                    result++;
                    continue;
                }
                if (number == 2) {
                    result++;
                    stack.push(new Point(i, j, number));
                }
            }
        }
        return result;
    }

    static class Point {
        private int x;
        private int y;
        private int val;

        public Point() {

        }

        public Point(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }
    }
}

29 给你一个餐馆信息数组 restaurants,其中  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]。你必须使用以下三个过滤器来过滤这些餐馆信息。

其中素食者友好过滤器 veganFriendly 的值可以为 true 或者 false,如果为 true 就意味着你应该只包括 veganFriendlyi 为 true 的餐馆,为 false 则意味着可以包括任何餐馆。此外,我们还有最大价格 maxPrice 和最大距离 maxDistance 两个过滤器,它们分别考虑餐厅的价格因素和距离因素的最大值。

过滤后返回餐馆的 id,按照 rating 从高到低排序。如果 rating 相同,那么按 id 从高到低排序。简单起见, veganFriendlyi 和 veganFriendly 为 true 时取值为 1,为 false 时,取值为 0 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/filter-restaurants-by-vegan-friendly-price-and-distance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FilterRestaurants {

    public static void main(String[] args) {
        //[[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]]
        //0
        //50
        //10
        int[][] restaurants = {
                {1, 4, 1, 40, 10},
                {2, 8, 0, 50, 5},
                {3, 8, 1, 30, 4},
                {4, 10, 0, 10, 3},
                {5, 1, 1, 15, 1}
        };
        int veganFriendly = 0;
        int maxPrice = 50;
        int maxDistance = 10;
        List<Integer> integerList = filterRestaurants(restaurants, veganFriendly, maxPrice, maxDistance);
        System.out.println(JSONObject.toJSONString(integerList));
    }

    public static List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
        List<Restaurant> restaurantList = new ArrayList<>();
        for (int i = 0; i < restaurants.length; i++) {
            int[] res =  restaurants[i];
             Restaurant restaurant=new Restaurant(res[0],res[1],res[2],res[3],res[4]);
             if(restaurant.getPrice() > maxPrice || restaurant.getDistance() > maxDistance){
                continue;
             }
             Integer veganFriend = restaurant.getVeganFriendly();
             if(veganFriendly==1 && veganFriend==0){
                 continue;
             }
             restaurantList.add(restaurant);
        }
       return restaurantList
                .stream()
                .sorted((restaurantNow, restaurantOther) -> {
                   int resVal = restaurantOther.getRating().compareTo(restaurantNow.getRating());
                   if (resVal != 0) {
                       return resVal;
                   }
                   return restaurantOther.getId().compareTo(restaurantNow.getId());
               })
               .map(Restaurant::getId).collect(Collectors.toList());
    }

    static class Restaurant {
        private Integer id;
        private Integer rating;
        private Integer veganFriendly;
        private Integer price;
        private Integer distance;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Integer getRating() {
            return rating;
        }

        public void setRating(Integer rating) {
            this.rating = rating;
        }

        public Integer getVeganFriendly() {
            return veganFriendly;
        }

        public void setVeganFriendly(Integer veganFriendly) {
            this.veganFriendly = veganFriendly;
        }

        public Integer getPrice() {
            return price;
        }

        public void setPrice(Integer price) {
            this.price = price;
        }

        public Integer getDistance() {
            return distance;
        }

        public void setDistance(Integer distance) {
            this.distance = distance;
        }

        public Restaurant() {

        }

        public Restaurant(Integer id,
                          Integer rating,
                          Integer veganFriendly,
                          Integer price,
                          Integer distance) {
            this.id = id;
            this.rating = rating;
            this.veganFriendly = veganFriendly;
            this.price = price;
            this.distance = distance;
        }
    }
}

30 给你一个字符串 s ,返回 s 中 长度为 3 的不同回文子序列 的个数。

即便存在多种方法来构建相同的子序列,但相同的子序列只计数一次。

回文 是正着读和反着读一样的字符串。

子序列 是由原字符串删除其中部分字符(也可以不删除)且不改变剩余字符之间相对顺序形成的一个新字符串。

例如,"ace" 是 "abcde" 的一个子序列。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/unique-length-3-palindromic-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 public static int countPalindromicSubsequence(String s) {
        Set<String> charSet = new HashSet<>();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            for (int j = i + 1; j < chars.length; j++) {
                for (int k = j + 1; k < chars.length; k++) {
                    if (chars[i] == chars[k]) {
                        String str = chars[i] + "" + chars[j] + "" + chars[k];
                        charSet.add(str);
                    }
                }
            }
        }
        return charSet.size();
    }

31 设计一个包含一些单词的特殊词典,并能够通过前缀和后缀来检索单词。

实现 WordFilter 类:

WordFilter(string[] words) 使用词典中的单词 words 初始化对象。
f(string pref, string suff) 返回词典中具有前缀 prefix 和后缀 suff 的单词的下标。如果存在不止一个满足要求的下标,返回其中 最大的下标 。如果不存在这样的单词,返回 -1 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/prefix-and-suffix-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import java.util.ArrayList;
import java.util.List;

public class WordFilter {

    List<String> wordList = new ArrayList<String>();

    public WordFilter(String[] words) {
        for (int i = 0; i < words.length; i++) {
            wordList.add(words[i]);
        }
    }

    public int f(String pref, String suff) {
        int index = -1;
        for (int i = 0; i < wordList.size(); i++) {
            String word = wordList.get(i);
            if (word.startsWith(pref) && word.endsWith(suff) && i > index) {
                index = i;
            }
        }
        return index;
    }
}

32 给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。

美式键盘 中:

第一行由字符 "qwertyuiop" 组成。
第二行由字符 "asdfghjkl" 组成。
第三行由字符 "zxcvbnm" 组成。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/keyboard-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class FindWords {
    public static void main(String[] args) {
        String[] words = {"Hello", "Alaska", "Dad", "Peace"};
        System.out.println(JSONObject.toJSONString(findWords(words)));
    }

    public static String[] findWords(String[] words) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            String st = words[i];
            if (wordAllIn(st)) {
                result.add(st);
            }
        }
        String[] res = new String[result.size()];
        result.toArray(res);
        return res;
    }

    public static boolean wordAllIn(String allStrIn) {
        char[] chars = allStrIn.toCharArray();
        String[] tables = new String[]{"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        boolean flag;
        for (int i = 0; i < tables.length; i++) {
            flag = true;
            String table = tables[i];
            for (int j = 0; j < chars.length; j++) {
                char aChar = chars[j];
                String tab = String.valueOf(aChar).toLowerCase(Locale.ROOT);
                if (!table.contains(tab)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return true;
            }
        }
        return false;
    }
}

 33 给定一个由 4 位数字组成的数组,返回可以设置的符合 24 小时制的最大时间。

24 小时格式为 "HH:MM" ,其中 HH 在 00 到 23 之间,MM 在 00 到 59 之间。最小的 24 小时制时间是 00:00 ,而最大的是 23:59 。从 00:00 (午夜)开始算起,过得越久,时间越大。

以长度为 5 的字符串,按 "HH:MM" 格式返回答案。如果不能确定有效时间,则返回空字符串。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/largest-time-for-given-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class LargestTimeFromDigits {

    public static void main(String[] args) {
        int[] arr = new int[]{2, 0, 6, 6};
        System.out.println(largestTimeFromDigits(arr));
    }

    public static String largestTimeFromDigits(int[] arr) {
        List<Integer> intSet = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            intSet.add(arr[i]);
        }
        List<Integer> arrList = intSet
                .stream()
                .sorted((o1, o2) -> o2 - o1)
                .collect(Collectors.toList());
        List<Integer> secondList=new ArrayList<>(arrList);
        String startWith = getStartWith(arrList, 0, 2);
        if (startWith.length() > 0) {
            return startWith;
        }
        return getStartWith(secondList, 0, 1);
    }

    public static String getStartWith(List<Integer> arrList, Integer min, Integer max) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getNumber(min, max, arrList));
        int parseInt = Integer.parseInt(stringBuilder.toString().equals("null") ? "-1" : stringBuilder.toString());
        if (parseInt == 2) {
            stringBuilder.append(getNumber(0, 3, arrList));
        }
        if (parseInt < 2) {
            stringBuilder.append(getNumber(0, 9, arrList));
        }
        stringBuilder.append(":");
        stringBuilder.append(getNumber(0, 5, arrList));
        stringBuilder.append(getNumber(0, 9, arrList));
        try {
            DateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            simpleDateFormat.parse(stringBuilder.toString());
        } catch (Exception e) {
            return "";
        }
        return stringBuilder.toString();
    }

    public static Integer getNumber(int min, int max, List<Integer> arrList) {
        Integer result = null;
        for (int i = 0; i < arrList.size(); i++) {
            Integer number = arrList.get(i);
            if (number >= min && number <= max) {
                arrList.remove(i);
                return number;
            }
        }
        return result;
    }
}

34 给你一个二维矩阵 matrix 和一个整数 k ,矩阵大小为 m x n 由非负整数组成。

矩阵中坐标 (a, b) 的 值 可由对所有满足 0 <= i <= a < m 且 0 <= j <= b < n 的元素 matrix[i][j](下标从 0 开始计数)执行异或运算得到。

请你找出 matrix 的所有坐标中第 k 大的值(k 的值从 1 开始计数)。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-kth-largest-xor-coordinate-value (超时)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  

import java.util.Deque;
import java.util.PriorityQueue;

public class KthLargestValue {

    public static void main(String[] args) {
       int[][] matrix = {{5, 2}, {1, 6}};
        int k = 1;
        System.out.println(kthLargestValue(matrix, k));
    }

    public static int kthLargestValue(int[][] matrix, int k) {
        int[][] xormatrix = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < xormatrix.length; i++) {
            for (int j = 0; j < xormatrix[0].length; j++) {
                xormatrix[i][j] = getXorNumber(i, j, matrix);
            }
        }
        PriorityQueue<Integer> xorPriro = new PriorityQueue<Integer>();
        for (int i = 0; i < xormatrix.length; i++) {
            for (int j = 0; j < xormatrix[0].length; j++) {
                int number = xormatrix[i][j];
                if (xorPriro.size() < k) {
                    xorPriro.add(number);
                    continue;
                }
                Integer peek = xorPriro.peek();
                if (peek < number) {
                    xorPriro.poll();
                    xorPriro.add(number);
                }
            }
        }
        return xorPriro.poll();
    }

    private static int getXorNumber(int x, int y, int[][] matrix) {
        int number = matrix[0][0];
        for (int i = 0; i <= x; i++) {
            for (int j = 0; j <= y; j++) {
                if (i > 0 || j > 0) {
                    number ^= matrix[i][j];
                }
            }
        }
        return number;
    }
}

35  给你一个下标从 0 开始的字符串数组 words 。

如果两个字符串由相同的字符组成,则认为这两个字符串 相似 。

例如,"abca" 和 "cba" 相似,因为它们都由字符 'a'、'b'、'c' 组成。然而,"abacba" 和 "bcfd" 不相似,因为它们不是相同字符组成的。请你找出满足字符串 words[i] 和 words[j] 相似的下标对 (i, j) ,并返回下标对的数目,其中 0 <= i < j <= word.length - 1 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-pairs-of-similar-strings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class SimilarPairs {
    public static void main(String[] args) {
        String[] words = {"aba", "aabb", "abcd", "bac", "aabc"};
        System.out.println(similarPairs(words));
    }

    public static int similarPairs(String[] words) {
        int count = 0;
        for (int i = 0; i < words.length; i++) {
            String wordsA = words[i];
            Set<Character> characterSetOne = buildSet(wordsA);
            for (int j = i + 1; j < words.length; j++) {
                String wordsB = words[j];
                Set<Character> characterSetTwo = buildSet(wordsB);
                if (similerAandB(characterSetOne, characterSetTwo)) {
                    count++;
                }
            }
        }
        return count;
    }

    private static Set<Character> buildSet(String wordsA) {
        Set<Character> characterSet = new HashSet<>();
        char[] chars = wordsA.toCharArray();
        for (char indec : chars) {
            characterSet.add(indec);
        }
        return characterSet;
    }

    public static boolean similerAandB(Set<Character> characterSetOne, Set<Character> characterSetTwo) {
        if (!characterSetOne.containsAll(characterSetTwo)) {
            return false;
        }
        if (!characterSetTwo.containsAll(characterSetOne)) {
            return false;
        }
        return true;
    }
}

36  编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""

import org.apache.commons.lang3.StringUtils;

public class LongestCommonPrefix {
    //["",""]

    public static void main(String[] args) {
        String[] strsPrefix = {"flower","flower","flower","flower"};
        String  result = longestCommonPrefix(strsPrefix);
        System.out.println(result);
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length <=1) {
            return strs[0];
        }
        String result = "";
        String number = strs[0];
        for (int i = 0; i <= number.length(); i++) {
            String numbers = number.substring(0,i);
            int count=0;
            for (int j = 0; j < strs.length; j++) {
                String word = strs[j];
                if (word.startsWith(numbers)
                        && numbers.length() > 0) {
                    count++;
                }
            }
            if (count == strs.length) {
                result = numbers;
            }
        }
        return result;
    }
}

37 以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-intervals
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Merge {

    public static void main(String[] args) {
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        System.out.println(JSONObject.toJSONString(merge(intervals)));
    }

    public static int[][] merge(int[][] intervals) {
        List<Point> pointList = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            int x = intervals[i][0];
            int y = intervals[i][1];
            pointList.add(new Point(x, y));
        }
        //合并所有的集合
        mergePoint(pointList);
        int[][] result = new int[pointList.size()][2];
        for (int i = 0; i < pointList.size(); i++) {
            Point point = pointList.get(i);
            int[] resultnew = new int[2];
            resultnew[0] = point.x;
            resultnew[1] = point.y;
            result[i] = resultnew;
        }
        return result;
    }

    private static void mergePoint(List<Point> pointList) {
        pointList.sort(Comparator.comparingInt(o -> o.x));
        if (!hasMergePoint(pointList)) {
            return;
        }
        for (int i = 0; i < pointList.size(); i++) {
            if ((i + 1) < pointList.size()) {
                Point pointOne = pointList.get(i);
                Point pointTwo = pointList.get(i + 1);
                if (pointOne.getY() >= pointTwo.getX()) {
                    pointList.remove(pointOne);
                    pointList.remove(pointTwo);
                    pointList.add(new Point(pointOne.x, Math.max(pointTwo.y, pointOne.y)));
                    break;
                }
            }
        }
        mergePoint(pointList);
    }

    private static boolean hasMergePoint(List<Point> pointList) {
        for (int i = 0; i < pointList.size(); i++) {
            if ((i + 1) < pointList.size()) {
                Point pointOne = pointList.get(i);
                Point pointTwo = pointList.get(i + 1);
                if (pointOne.getY() >= pointTwo.getX()) {
                    return true;
                }
            }
        }
        return false;
    }

    static class Point {
        private int x;
        private int y;

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

        public Point() {

        }

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}

38 给你一个下标从 0 开始的字符串数组 words 以及一个二维整数数组 queries 。

每个查询 queries[i] = [li, ri] 会要求我们统计在 words 中下标在 li 到 ri 范围内(包含 这两个值)并且以元音开头和结尾的字符串的数目。

返回一个整数数组,其中数组的第 i 个元素对应第 i 个查询的答案。

注意:元音字母是 'a'、'e'、'i'、'o' 和 'u' 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-vowel-strings-in-ranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class VowelStrings {


    public static void main(String[] args) {
       String[] words = {"aba","bcb","ece","aa","e"};
       int[][] queries = {{0,2},{1,4},{1,1}};
       int[] wos = vowelStrings(words, queries);
       System.out.println(JSONObject.toJSONString(wos));
    }


    public static int[] vowelStrings(String[] words, int[][] queries) {
        int[] count=new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int start = queries[i][0];
            int end = queries[i][1];
            for (int j = start; j <= end; j++) {
                String wos = words[j];
                if(isAeiou(wos)){
                    count[i]++;
                }
            }
        }
        return count;
    }

    public static boolean isAeiou(String wos) {
        List<Character> characterList = new ArrayList<>();
        characterList.add('a');
        characterList.add('e');
        characterList.add('i');
        characterList.add('o');
        characterList.add('u');
        char start = wos.charAt(0);
        char end = wos.charAt(wos.length() - 1);
        if (characterList.contains(start)
                && characterList.contains(end)) {
            return true;
        }
        return false;
    }
}

39 给你一个整数数组 nums ,和一个表示限制的整数 limit,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit 。

如果不存在满足条件的子数组,则返回 0 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class LongestSubarray {

    public static void main(String[] args) {
        int[] nums = {10,1,2,4,7,2};
        int limit = 5;
        int count = longestSubarray(nums, limit);
        System.out.println(count);
    }

    public static int longestSubarray(int[] nums, int limit) {
        List<List<Integer>> listList = getAllSubArray(nums);
        return getNumber(listList, limit);
    }

    private static int getNumber(List<List<Integer>> listList, int limit) {
        List<List<Integer>> allArrayLenth = listList
                .stream()
                .map(item -> {
                    int max = getMax(item);
                    int min = getMin(item);
                    if (Math.abs((max - min)) <= limit) {
                        return item;
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        int len = Integer.MIN_VALUE;
        for (int i = 0; i < allArrayLenth.size(); i++) {
            List<Integer> list = allArrayLenth.get(i);
            if (list.size() > len) {
                len = list.size();
            }
        }
        return len;
    }

    public static int getMin(List<Integer> item) {
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < item.size(); i++) {
            if (result > item.get(i)) {
                result = item.get(i);
            }
        }
        return result;
    }

    public static int getMax(List<Integer> item) {
        int result = Integer.MIN_VALUE;
        for (int i = 0; i < item.size(); i++) {
            if (result < item.get(i)) {
                result = item.get(i);
            }
        }
        return result;
    }

    public static List<List<Integer>> getAllSubArray(int[] nums) {
        List<List<Integer>> listList = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j <= nums.length; j++) {
                  int[] newArray=new int[j-i];
                  System.arraycopy(nums,i,newArray,0,j-i);
                  List<Integer>  newArr=new ArrayList<>();
                  for(int k=0;k<newArray.length;k++){
                       int numberK = newArray[k];
                      newArr.add(numberK);
                  }
                listList.add(newArr);
            }
        }
        return listList;
    }


}

40  给你一个数组 rectangles ,其中 rectangles[i] = [li, wi] 表示第 i 个矩形的长度为 li 、宽度为 wi 。如果存在 k 同时满足 k <= li 和 k <= wi ,就可以将第 i 个矩形切成边长为 k 的正方形。例如,矩形 [4,6] 可以切成边长最大为 4 的正方形。

设 maxLen 为可以从矩形数组 rectangles 切分得到的 最大正方形 的边长。

请你统计有多少个矩形能够切出边长为 maxLen 的正方形,并返回矩形 数目 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-rectangles-that-can-form-the-largest-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

package worn.xiao;

import java.util.ArrayList;
import java.util.List;

public class CountGoodRectangles {
    public static void main(String[] args) {
        //[[5,8],[3,9],[3,12]]
        int[][] rectangles = {{5, 8}, {3, 9}, {3, 12}};
        System.out.println(countGoodRectangles(rectangles));
    }

    public static int countGoodRectangles(int[][] rectangles) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < rectangles.length; i++) {
            int x = rectangles[i][0];
            int y = rectangles[i][1];
            list.add(Math.min(x, y));
        }
        list.sort((o1, o2) -> o2 - o1);
        int result = 0;
        Integer max = list.get(0);
        for (int i = 0; i < list.size(); i++) {
            Integer number = list.get(i);
            if (number.equals(max)) {
                result++;
            }
        }
        return result;
    }
}

41 「句子」是一个用空格分隔单词的字符串。给你一个满足下述格式的句子 text :

  • 句子的首字母大写
  • text 中的每个单词都用单个空格分隔。

请你重新排列 text 中的单词,使所有单词按其长度的升序排列。如果两个单词的长度相同,则保留其在原句子中的相对顺序。

请同样按上述格式返回新的句子。

import java.util.*;
import java.util.stream.Collectors;

public class ArrangeWords {

    public static void main(String[] args) {
        String text = "Leetcode is cool";
        System.out.println(arrangeWords(text));
    }

    public static String arrangeWords(String text) {
        String[] splitWord = text.split(" ");
        List<String> containers = new ArrayList<>();
        for (int i = 0; i < splitWord.length; i++) {
            String wors = splitWord[i];
            containers = insertToContainer(containers, wors);
        }
        List<String> contains = containers
                .stream()
                .map(item -> item.toLowerCase(Locale.ROOT))
                .collect(Collectors.toList());
        String con = contains.get(0);

        String subStr = con.substring(0, 1)
                .toUpperCase(Locale.ROOT)
                .concat(con.substring(1));
        List<String> result = new ArrayList<>();
        for (int i = 0; i < contains.size(); i++) {
            if (i == 0) {
                result.add(subStr);
                continue;
            }
            result.add(contains.get(i));
        }
        return result
                .stream()
                .collect(Collectors.joining(" "));
    }

    public static List<String> insertToContainer(List<String> containers, String wors) {
        if (containers.size() <= 0) {
            containers.add(wors);
            return containers;
        }
        return sortContainer(containers, wors);
    }

    /**
     * 插入排序
     *
     * @param containers
     * @param wors
     */
    public static List<String> sortContainer(List<String> containers, String wors) {
        List<String> result = new ArrayList<>();
        List<String> words = Arrays.asList(wors);
        int i = 0;
        int j = 0;
        while (i < containers.size() && j < words.size()) {
            String s = containers.get(i);
            String s1 = words.get(j);
            if (s.length() <= s1.length()) {
                result.add(s);
                i++;
            }
            if (s.length() > s1.length()) {
                result.add(s1);
                j++;
            }
        }
        while (i < containers.size()) {
            String con = containers.get(i);
            result.add(con);
            i++;
        }
        while (j < words.size()) {
            String wor = words.get(j);
            result.add(wor);
            j++;
        }
        return result;
    }
}

42 给你一个下标从 0 开始的整数数组 nums 。请你从 nums 中找出和 最大 的一对数,且这两个数数位上最大的数字相等。

返回最大和,如果不存在满足题意的数字对,返回 -1 。 

public class MaxSum {

    public static void main(String[] args) {
        int[] nums = {51, 71, 17, 24, 42};
        System.out.println(maxSum(nums));
    }

    public static int maxSum(int[] nums) {
        int number = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int numberx = nums[i];
            for (int j = i+1; j < nums.length; j++) {
                int numbery = nums[j];
                if (!eqmax(numberx, numbery)) {
                    continue;
                }
                int numbers = (numberx + numbery);
                if (numbers > number) {
                    number = numbers;
                }
            }
        }
        if (number < 0) {
            return -1;
        }
        return number;
    }

    public static boolean eqmax(int numberx, int numbery) {
        String numer = String.valueOf(numberx);
        String numb = String.valueOf(numbery);
        char[] charArrayX = numer.toCharArray();
        char[] charArrayY = numb.toCharArray();
        Character maxNunX = getMaxNun(charArrayX);
        Character maxNunY = getMaxNun(charArrayY);
        if (maxNunX == maxNunY) {
            return true;
        }
        return false;
    }

    public static Character getMaxNun(char[] charArrayX) {
        Character character = charArrayX[0];
        for (int i = 0; i < charArrayX.length; i++) {
            Character numcher = charArrayX[i];
            if (numcher - character > 0) {
                character = numcher;
            }
        }
        return character;
    }
}

3. 无重复字符的最长子串

 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

 

public class LengthOfLongestSubstring {
    public static void main(String[] args) {
        String str = "pwwkew";
        System.out.println(lengthOfLongestSubstring(str));
    }

    public static int lengthOfLongestSubstring(String str) {
        if(str.length()<=0){
            return 0;
        }
        int max =Integer.MIN_VALUE;
        for (int i = 0; i < str.length(); i++) {
            StringBuilder strb = new StringBuilder();
            int result=0;
            for (int j = i; j < str.length(); j++) {
                String cha = str.charAt(j) + "";
                if(strb.toString().contains(cha)){
                   break;
                }
                strb.append(cha);
                result++;
            }
            if(result>max){
                max=result;
            }
        }
        return max;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值