leetcode Two Sum 解决思路
来源:互联网 发布:org.apache.struts2 编辑:程序博客网 时间:2024/06/11 07:18
/* * Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. 给出一个int数组,返回数组中两个数下标,这两个数相加等于一个给出的int数,每个数只能用一次,不能自己加自己Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. 例如: 条件: nums = [2, 7, 11, 15], target = 9, 满足: nums[0] + nums[1] = 2 + 7 = 9, 返回 : [0, 1]. */public class Solution {public static int[] twoSum1(int[] nums, int target) {if (nums == null) {return null;}// 返回值int result[] = new int[2];// 遍历for (int i = 0; i < nums.length; i++) {// 从当前下标下一位数开始遍历 不会自己加自己for (int j = i + 1; j < nums.length; j++) {// 如果相加等于目标 就返回当前i jif (nums[i] + nums[j] == target) {result[0] = i;result[1] = j;}}}return result;}public static int[] twoSum2(int[] nums, int target) {if (nums == null) {return null;}// 返回值int result[] = new int[2];// 这个map用来存放已经遍历过的数据 (不用进行双层循环)Map<Integer, Integer> gone = new HashMap<>();// 遍历数字数组for (int i = 0; i < nums.length; i++) {// 如果已经遍历过的数中存在一个与当前数相加等于target 则返回两位数的下标if (gone.containsKey(target - nums[i])) {result[0] = gone.get(target - nums[i]);result[1] = i;}gone.put(nums[i], i);}return result;}public static void main(String[] args) {//测试int ints [] ={3,2,4};int targrt = 6;int res[] = twoSum1(ints,targrt);int res2[] = twoSum2(ints,targrt);if(res != null){for (int i = 0; i < res.length; i++) {System.out.print("第"+(i+1)+"个下标:"+res[i]+" ");}}System.out.println();if(res2 != null){for (int i = 0; i < res2.length; i++) {System.out.print("第"+(i+1)+"个下标:"+res2[i]+" ");}}}}
阅读全文
2 0
- leetcode Two Sum 解决思路
- leetcode 之 Two Sum 解题思路
- LeetCode- 1. Two Sum - 思路详解-C++
- leetcode Add Two Numbers 解决思路
- leetCode 1. Two Sum 解题思路和方法
- 【LeetCode】1.Two Sum思路以及知识点复习
- 【Leetcode】Two Sum (Sum)
- 用java解决LeetCode(1)——Two Sum
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- 合并两个有序链表
- 杨辉三角
- SQL学习笔记:表的约束
- List ADT的两种实现方式:ArrayList和LinkedList
- C++ 从函数返回指针(函数外返回局部静态变量的地址)
- leetcode Two Sum 解决思路
- poj3693(后缀数组+lcp+rmq)
- 170718 Linux 文件路径切换与查找
- HDU
- 正则表达式常用验证
- laravel5.4开启sql调试
- web错误集锦(自看)
- 浅谈HTML5 postMessage
- PHP数据类型转换(字符转数字,数字转字符)