zoukankan      html  css  js  c++  java
  • Lc1- 两数之和

    刷题顺序:https://cspiration.com/leetcodeClassification
    
    
    题目解析:通过结果与当前值做差与剩余的数字对比,如果相等则存在俩数之和等于结果;这里选择map这种数据结构,key存值,value记录位置。
    
    
    

    import java.util.LinkedHashMap; import java.util.Map; /* * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Lc1 { /** * @param nums * @param target * @return */ public static int[] twoSum(int[] nums, int target) { // value 值,value 位置 Map
    <Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); int[] res = new int[2]; for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { res[0] = map.get(target - nums[i]); res[1] = i; } else { map.put(nums[i], i); } } return res; } public static void main(String[] args) { int[] nums = { 3, 3 }; int target = 6; int[] res = twoSum(nums, target); System.out.println(res[0]); System.out.println(res[1]); } }
  • 相关阅读:
    String驻留带来的危害
    Go语言的堆栈分析
    SecureCRT使用技巧
    Javascript中相同Function使用多个名称
    记录Office Add-in开发经验
    Silverlight和WPF中DataContractJsonSerializer对时间的处理差异
    ASP.NET MVC项目实践技巧
    有点担心Node.js的未来了
    回首经典的SQL Server 2005
    duilib关于学习Demo中的QQ
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12124181.html
Copyright © 2011-2022 走看看