AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-23993901

CodeCrusader's questions

Martin Hope
CodeCrusader
Asked: 2025-04-29 00:52:43 +0800 CST

找到相邻 diff 小于 2 的子序列的最大长度

  • 8

问题陈述:

给定一个大小为 n 的整数数组 arr。

选择一个整数子序列并重新排列它们以形成一个循环序列,使得任意两个相邻整数(包括最后一个和第一个)之间的绝对差最多为 1。

找出可以选择的最大整数数。

笔记:

子序列是通过删除零个或多个元素而不改变剩余元素的顺序而形成的。

选定的整数可以按任意顺序重新排列。

该序列是循环的——最后一个整数和第一个整数被视为相邻的。

限制:

1 <= n <= 2 × 10^5

0 <= arr[i] <= 10^9

例子:

Input: arr = [4, 3, 5, 1, 2, 2, 1]
Output: 5
Explanation: maximum length subsequence is : [3, 1, 2, 2, 1], it can be rearranged to seq : [2, 1, 1, 2, 3] of length 5, note that the condition must be satisfied in circular also, means abs(seq[0] - seq[seq.length-1]) means abs(2-3) <= 0 

Input: arr = [3, 7, 5, 1, 5]
Output: 2
Explanation: maximum length subsequence is : [5,5] of length 2

Input: arr = [2, 2, 3, 2, 1, 2, 2]
Output: 7
Explanation: maximum length subsequence is : [2,2,3,2,1,2,2] of length 7

Input: arr = [1,2,3,4,5]
Output = 2
Explanation: maximum length subsequence is : [1,2] or [2,3] or [3,4] or [4,5], so length is 2. 

请注意,子序列也应该满足循环条件这是我的代码:

import java.util.*;

class Main {
    public static int solve(int[] arr) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int num : arr) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }

        int max = 0;
        for (int num : freq.keySet()) {
            int count = freq.get(num);
            int countWithNext = freq.getOrDefault(num + 1, 0);
            int countWithPrev = freq.getOrDefault(num - 1, 0);
            max = Math.max(max, countWithPrev + count + countWithNext);
        }

        return max;
    }

    public static void main(String[] args) {
        System.out.println(solve(new int[]{4,3,5,1,2,2,1})); // Expected: 5
        System.out.println(solve(new int[]{3,7,5,1,5})); // Expected: 2
        System.out.println(solve(new int[]{2,2,3,2,1,2,2})); // Expected: 7
        System.out.println(solve(new int[]{1,2,3,4,5})); // Expected: 2
    }
}

我能够找到最大长度子序列,但无法找到如何满足循环条件,因此对于测试用例 [1,2,3,4,5],我的代码返回 5 而不是 2。

此外,正如 John Bollinger 所评论的,该方法本身对于输入 [1,2,3,4,3,2] 失败

用较少的时间复杂度来解决这个问题的正确方法是什么?

java
  • 2 个回答
  • 109 Views
Martin Hope
CodeCrusader
Asked: 2025-03-07 04:17:07 +0800 CST

找到排序顺序的最少操作

  • 7

任务描述为:

我有一个从 1 到 n 的不同数字数组,例如 arr = [5, 3, 4, 1, 2]

将名为 order 的变量初始化为 1,现在从左到右遍历数组并查找与变量 order 匹配的元素,如果找到则增加 order 并向前移动。换句话说,我们可以说将名为 order 的变量初始化为 1,因此首先从左到右遍历数组并查看 1 在数组中出现的位置,然后将 order 增加到 2,然后在数组中向前移动并查找 2,如果找到则将 order 增加到 3。像上面那样从左到右迭代称为操作

当 arr = [5,3,4,1,2] 时,从左到右依次遍历,当找到 arr[3] 时,order 的值从 1 变为 2,当找到 arr[4] 时,order 的值从 2 变为 3

重复上述步骤,直到变量阶达到值n。重复的次数称为操作。

因此当 arr [ 5,3,4,1,2] 时,所需的最少操作数为 3

import java.util.*;

class Main {
    public static int solve(List<Integer> arr) {
        int n = arr.size();
        int order = 0; // Number of sorted items found
        int operations = 0;  // Count of full array scan
        
        while (sortedCount < n) {
            order++;
            for (int i = 0; i < n; i++) {
                if (arr.get(i) == order + 1) {
                    order++;
                }
            }
        }        
        return operations;
    }

    public static void main(String[] args) {
        System.out.println(solve(Arrays.asList(5, 3, 4, 1, 2))); // Output: 3
        System.out.println(solve(Arrays.asList(3,1,4,2,5))); // Output: 2
        System.out.println(solve(Arrays.asList(1,2,3,4))); // Output: 1
        System.out.println(solve(Arrays.asList(2,1))); // Output: 2
    }
}

我的代码运行时间为 O(n^2),我们如何才能以更低的时间复杂度解决这个问题

java
  • 3 个回答
  • 89 Views
Martin Hope
CodeCrusader
Asked: 2025-01-23 05:09:04 +0800 CST

给定任务,程序员在更短的时间内解决任务

  • 5

我有一个大小为的任务列表n,处理所需的时间表示为tasks[i],其中i是任务的索引。

处理步骤:i = 0这些任务应按从到的顺序i = n-1一个接一个地进行处理。

现在有另一个大小为 的程序员列表m,他们可以在 所表示的指定时间内完成任务programmers[i],其中i是索引。

如果任务的值为 0,则表示任务已完成,否则该任务为待处理任务。

因此,如果上述处理步骤结束时仍有一些任务待处理,则处理应从到重新i = 0开始i = n-1

如果所有任务都完成了,那么我们可以重新加载任务并从头开始处理。

我想收集每个程序员在指定的时间内工作后仍有多少任务处于待处理状态。

以下是一个例子:

示例 1

n=5,任务= [2, 4, 5, 1, 1] m=5,程序员=[1, 5, 1, 5, 2]

程序员 任务 待处理任务
1 [1, 4, 5, 1, 1] 第一项任务已部分处理,总待处理任务数 = 5
2 [0, 0, 5, 1, 1] 前两个任务已全部处理完毕,总待处理任务数 = 3
3 [0, 0, 4, 1, 1] 第三项任务已部分处理,总待处理任务数 = 3
4 [0, 0, 0, 0, 1] 第三和第四个任务已全部处理完毕,总待处理任务数 = 1
5 [0, 0, 0, 0, 0] 最后一项任务已全部处理完毕,待处理任务总数 = 0

因此,待处理任务的数量 =[5, 3, 3, 1, 0]

示例 2

任务 =[1, 2, 4, 1, 2] 程序员 =[3, 10, 1, 1, 1]

程序员 任务 待处理任务
1 [0, 0, 4, 1, 2] 第一和第二个任务已全部处理完毕,总待处理任务数 = 3
2 [0, 0, 0, 0, 0] 所有任务均已完全处理,待处理任务总数 = 0(待处理任务为 0,因此加载回所有任务[1,2,4,1,2])
3 [0, 2, 4, 1, 2] 第一个任务已完全处理,总待处理任务数 = 4
4 [0, 1, 4, 1, 2] 第二项任务已部分处理,待处理任务总数 = 4
5 [0, 0, 3, 1, 2] 第二项任务已全部处理完毕,待处理任务总数 = 3

输出 =[3,0,4,4,3]

示例 3

任务 =[1, 4, 4] 程序员 =[9, 1, 4]

输出 =[0, 2, 1]

以下是我在 O(m*n) 时间内运行的代码:

import java.util.*;

public class Main {

    public static List<Integer> getPendingTasks(List<Integer> tasks, List<Integer> programmers) {
        List<Integer> pendingTasks = new ArrayList<>();
        List<Integer> originalTasks = new ArrayList<>(tasks); // Save original tasks for reloading
        int n = tasks.size();
        
        for (int programmer : programmers) {
            int timeRemaining = programmer;
            for (int i = 0; i < n && timeRemaining > 0; i++) {
                if (tasks.get(i) > 0) {
                    if (tasks.get(i) <= timeRemaining) {
                        timeRemaining -= tasks.get(i);
                        tasks.set(i, 0);
                    } else {
                        tasks.set(i, tasks.get(i) - timeRemaining);
                        timeRemaining = 0;
                    }
                }
            }

            // Count pending tasks
            int pending = 0;
            for (int task : tasks) {
                if (task > 0) {
                    pending++;
                }
            }

            pendingTasks.add(pending);

            // Reload tasks if all are completed
            if (pending == 0) {
                tasks = new ArrayList<>(originalTasks);
            }
        }

        return pendingTasks;
    }

    public static void main(String[] args) {
        // Example 1
        List<Integer> tasks1 = Arrays.asList(2, 4, 5, 1, 1);
        List<Integer> programmers1 = Arrays.asList(1, 5, 1, 5, 2);
        System.out.println("Output: " + getPendingTasks(tasks1, programmers1)); // Output: [5, 3, 3, 1, 0]

        // Example 2
        List<Integer> tasks2 = Arrays.asList(1, 2, 4, 1, 2);
        List<Integer> programmers2 = Arrays.asList(3, 10, 1, 1, 1);
        System.out.println("Output: " + getPendingTasks(tasks2, programmers2)); // Output: [3, 0, 4, 4, 3]

        // Example 3
        List<Integer> tasks3 = Arrays.asList(1, 4, 4);
        List<Integer> programmers3 = Arrays.asList(9, 1, 4);
        System.out.println("Output: " + getPendingTasks(tasks3, programmers3)); // Output: [0, 2, 1]
    }
}

我还尝试使用 PriorityQueue 仅处理待处理的任务:

import java.util.*;

class Main {

    public static List<Integer> getPendingTasks(List<Integer> tasks, List<Integer> programmer) {
        List<Integer> result = new ArrayList<>();
        Queue<Integer> pending = new PriorityQueue<>();
        int n = tasks.size();
        List<Integer> originalTasks = new ArrayList<>(tasks);

        // Initialize set with all tasks
        for (int i = 0; i < n; i++) {
            pending.add(i);
        }
        Queue<Integer> q = new PriorityQueue<>(pending);
        
        // Process each item
        for (int p : programmer) {
            int timeAvailable = p;

            // Process only unprocessed tasks
            List<Integer> balancedTask = new ArrayList<>();
            
            while (!q.isEmpty()) {
                int i = q.poll();
                if (tasks.get(i) <= timeAvailable) {
                    timeAvailable -= tasks.get(i);
                    // Task fully processed
                } else {
                    tasks.set(i, tasks.get(i) - timeAvailable); // Partially processed
                    timeAvailable = 0; // time exhausted
                    balancedTask.add(i);
                }
            }
            q.addAll(balancedTask);
            result.add(q.size());
            if(q.size() ==0) {
                tasks = originalTasks;
                q= pending;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(getPendingTasks(Arrays.asList(2, 4, 5, 1, 1), Arrays.asList(1, 5, 1, 5, 2))); 
        // Expected: [5, 3, 3, 1, 0]
        
        System.out.println(getPendingTasks(Arrays.asList(1, 2, 4, 1, 2), Arrays.asList(3, 10, 1, 1, 1))); 
        // Expected: [3, 0, 4, 4, 3]
        
        System.out.println(getPendingTasks(Arrays.asList(1, 4, 4), Arrays.asList(9, 1, 4))); 
        // Expected: [0, 2, 1]
    }
}

但是上面的代码也会在O(n*m*log(m))时间复杂度上运行

限制:

n and m in range 1 to 2 * 10^5
each item in input lists is 1 to 10^9

我想知道如何在较少的时间复杂度内解决这个问题

java
  • 1 个回答
  • 79 Views
Martin Hope
CodeCrusader
Asked: 2024-12-20 00:59:51 +0800 CST

查找大于另一个字符串的子序列的数量

  • 6

给定两个长度为 m 的字符串 s 和另一个长度为 n 的字符串 t,计算 s 中有多少个子序列大于 t

如果序列 p 满足以下情况,则称其大于另一个序列 q:

a) 在 p 和 q 不同的第一个位置,p[i] > q[i],或
b) |p| > |q| 且 q 是 p 的前缀(其中 |p| 表示密码 p 的长度)。

例子:

s="bab" t="ab"

结果= 5

解释:

Valid subsequences of s which are greater than t are
"b"
"ba"
"bb"
"bab"
"b"

限制: s 的长度为 1 到 10^5,t 的长度为 1 到 100

在有效组合的情况下,t 的长度可以大于 s 的长度。

我使用递归方法解决了这个问题,但时间复杂度为 O(2^n * n)。

public class Main {
    private static final int MOD = 1_000_000_007;

    private static void subsequence(String s, int index, String current, List<String> subsequences) {
        if (index == s.length()) {
            if (!current.isEmpty()) {
                subsequences.add(current);
            }
            return;
        }
        subsequence(s, index + 1, current, subsequences);
        subsequence(s, index + 1, current + s.charAt(index), subsequences);
    }

    private static boolean isGreater(String s1, String t) {
        int len1 = s1.length();
        int len2 = t.length();
        for (int i = 0; i < Math.min(len1, len2); i++) {
            if (s1.charAt(i) > t.charAt(i)) {
                return true;
            } else if (s1.charAt(i) < t.charAt(i)) {
                return false;
            }
        }
        return len1 > len2;
    }

    public static int solve(String s, String t) {
        List<String> subsequences = new ArrayList<>();
        subsequence(s, 0, "", subsequences);

        int count = 0;
        for (String e : subsequences) {
            if (isGreater(e, t)) {
                count = (count + 1) % MOD;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        System.out.println(solve("aba", "ab")); // Expected: 3
        System.out.println(solve("bab", "ab")); // Expected: 5
        System.out.println(solve("wrrmkhds", "bebbjvcgzlwtbvasphvm")); // Expected: 255
        System.out.println(solve("o", "h"));   // Expected: 1
    }
}

如何以较少的时间复杂度解决这个问题?

java
  • 2 个回答
  • 114 Views
Martin Hope
CodeCrusader
Asked: 2024-10-06 12:22:44 +0800 CST

查找有效子字符串的数量

  • 5

给定一个长度为 n 的字符串,我想计算有多少个子字符串可能具有以下特征:

a) 子串长度为偶数 b) 该子串中存在一个字符,其频率等于子串长度的一半。

例如 s="idafddfii", 输出 = 13

解释:

有效的子字符串为:“id”、“da”、“af”、“fd”、“df”、“fi”、“dafd”、“afdd”、“fddf”、“ddfi”、“dfii”、“idafdd”、“dafddf”

限制:

1 <= n <= 10 的 5 次方

s 仅由小写英文字母组成

public class Main {

    public static long solve(String s) {
        int n = s.length();
        long result = 0;
    
        for (int i = 0; i < n; i++) {
            int[] freq = new int[26];
            for (int j = i; j < n; j++) {
                freq[s.charAt(j) - 'a']++;
                int len = j - i + 1;
                // Only check even-length substrings
                if (len % 2 == 0) {
                    if (isValid(freq, len)) {
                        result++;
                    }
                }
            }
        }
        return result;
    }
    
    private static boolean isValid(int[] freq, int len) {
        int half = len / 2;
        for (int count : freq) {
            if (count == half) {
                return true;
            }
        }
        return false;
    }
    
    public static void main(String[] args) {
        String s1 = "aaaaid";
        String s2 = "aidfg";
        String s3 = "ababbab";
    
        System.out.println(solve(s1)); // Output: 3
        System.out.println(solve(s2)); // Output: 4
        System.out.println(solve(s3)); // Output: 8
    }

}

我的代码运行时间复杂度为 O(n^2),我想降低这个时间复杂度,在更短的时间内解决这个问题的正确方法是什么。

根据@Unmitigated 提供的答案,我尝试像这样构建每个字符的累积频率,但现在不知道如何使用这个累积频率来解决问题。

import java.util.*;
public class Main {

    public static int solve(String s) {
        int n = s.length();
        int result = 0;
        Map<Character, int[]> map = new HashMap<>();
        for(int i=0; i<n; i++) {
            char ch = s.charAt(i);
            int[] cnt = map.getOrDefault(ch, new int[n]);
            cnt[i] += i == 0 ? 1 : cnt[i-1]+1;
            map.put(ch, cnt);
        }
        for(char c : map.keySet()) {
            System.out.println(c + ":" + Arrays.toString(map.get(c)));
        } 
        // what to do next
        return result;
    }

    public static void main(String[] args) {
        String s = "idafddfii";
        int output = solve(s);
        System.out.println(output); // Output: 13
    }
}
java
  • 1 个回答
  • 115 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve