9.25-编程刷题

1.两数之和

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n=nums.length;
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<n;i++){
            if(map.containsKey(target-nums[i])){
                return new int[]{map.get(target-nums[i]),i};
            }else{
                map.put(nums[i],i);
            }
        }
        return new int[0];
    }
}

2.快乐数

java 复制代码
class Solution {
    public int getNext(int n){
        int totalSum=0;
        while (n>0){
            int temp=n%10;
            n=n/10;
            totalSum+=temp*temp;
        }
        return totalSum;
    }
    public boolean isHappy(int n) {
        Set<Integer> set=new HashSet<>();
        while (n!=1 && !set.contains(n)){
            set.add(n);
            n=getNext(n);
        }
        return n==1;
    }
}

3.存在重复元素 II

java 复制代码
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,ArrayList<Integer>> map=new HashMap<>();
        int n=nums.length;
        for(int i=0;i<n;i++){
            if(!map.containsKey(nums[i])){
                ArrayList<Integer> list=new ArrayList<>();
                list.add(i);
                map.put(nums[i],list);
            }else{
                ArrayList<Integer> integers = map.get(nums[i]);
                integers.add(i);
                map.put(nums[i],integers);
            }
        }
        for(Map.Entry<Integer,ArrayList<Integer>> entry: map.entrySet()){
            if(entry.getValue().size()>1){
                for(int i=0;i<entry.getValue().size()-1;i++){
                    if(entry.getValue().get(i+1)-entry.getValue().get(i)<=k){
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
java 复制代码
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            int num = nums[i];
            if (map.containsKey(num) && i - map.get(num) <= k) {
                return true;
            }
            map.put(num, i);
        }
        return false;
    }
}
相关推荐
yongui478341 天前
NSGA-II求解多目标柔性作业车间调度算法(含甘特图绘制)
算法·甘特图
故事和你911 天前
洛谷-算法2-1-前缀和、差分与离散化1
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
知识浅谈1 天前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了
算法
DeepModel1 天前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
田梓燊1 天前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
简简单单做算法1 天前
基于GA遗传优化双BP神经网络的时间序列预测算法matlab仿真
神经网络·算法·matlab·时间序列预测·双bp神经网络
阿豪学编程1 天前
面试题map/unordered相关
数据结构
guygg881 天前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
武藤一雄1 天前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
sali-tec1 天前
C# 基于OpenCv的视觉工作流-章52-交点查找
图像处理·人工智能·opencv·算法·计算机视觉