LeetCode【1】两数之和

题目:

代码:

java 复制代码
public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];

        Map<Integer, Integer> map = new HashMap<>();

//        for (int i = 0; i < nums.length; i++) {    // 这么写不能防重复啊!注意这里不要提前放好
//            map.put(nums[i], i);
//        }

        for (int i=0;i<nums.length;i++) {
            if (map.get(target-nums[i]) != null) {
                result[0] = i;
                result[1] = map.get(target-nums[i]);
            }
            map.put(nums[i], i);
        }
        return result;
    }   
相关推荐
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 739. 每日温度 | C++ 逆序单调栈
c++·算法·leetcode
良木生香3 小时前
【C++初阶】:STL——String从入门到应用完全指南(1)
c语言·开发语言·数据结构·c++·算法
XWalnut3 小时前
LeetCode刷题 day16
数据结构·算法·leetcode·链表·动态规划
foundbug9995 小时前
基于混合整数规划的电池容量优化 - MATLAB实现
数据结构·算法·matlab
chutao5 小时前
EasyPDF 转图片(EasyPdf2Image)—— 本地安全实用的PDF与图片双向互转工具
安全·职场和发展·pdf·创业创新·学习方法
海绵宝宝的月光宝盒5 小时前
2-非金属材料
经验分享·笔记·学习·其他·职场和发展·课程设计·制造
memcpy06 小时前
LeetCode 2452. 距离字典两次编辑以内的单词【暴力;字典树】中等
算法·leetcode·职场和发展
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【排序贪心】:魔法
c++·算法·贪心·csp·信奥赛·排序贪心·魔法
wearegogog1236 小时前
基于和差波束法的单脉冲测角MATLAB实现
人工智能·算法·matlab