Two Sum
来源:互联网 发布:电脑学习软件 编辑:程序博客网 时间:2024/06/06 04:40
题目:
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.
题意:
给出一个整数数组和一个数target,求出两个下标i,j,使得a[i]+a[j] = target,返回下标
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路:
1.最简单的两重循环,选定数组中的一个数a[i],再遍历数组,看是否有target-a[i],返回下标即可,时间复杂度为O(n2).
2.利用Java中的HashMap,循环遍历数组中的每个元素,利用HaspMap进行查找target-a[i],HaspMap的查找的时间复杂度为O(1),因此总的时间复杂度为O(n).
代码:
public class TwoSum { /* O(n2) */ public int[] twoSum(int []nums,int target){ int solution[] = new int[2]; for(int i = 0; i < nums.length; i++){ int temp = nums[i]; for(int j = 0; j < nums.length; j++){ if(j == i) continue; if(nums[j] == target-nums[i]){ if(i > j){ solution[0] = j; solution[1] = i; }else{ solution[0] = i; solution[1] = j; } i = nums.length+1; break; } } } return solution; } /* O(n) */ public int[] twoSum2(int []nums,int target){ int solution[] = new int[2]; Map<Integer,Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){ if(map.containsKey(target-nums[i])){ solution[1] = i; solution[0] = map.get(target-nums[i]); return solution; } map.put(nums[i],i); } return solution; } public static void main(String[] args) { int nums[] = {2,7,11,15}; int solution[] = new TwoSum().twoSum2(nums,9); System.out.println(solution[0] + " " + solution[1]); }}
0 0
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- 在应用内打开外部系统工具
- spring相关技术整理
- CSS学习笔记:1 基础语法
- 事物冲突
- Android--手机卫士涉及的知识点总结(五)
- Two Sum
- javascript自制alert提示框
- 欢迎使用CSDN-markdown编辑器
- java-jvm-jstack-(监视器和锁的概念)
- BZOJ4810 [Ynoi2017]由乃的玉米田
- 编译环境搭建计划(2017.4.7 ~ 2017.4.9)
- NCV63-portal单点登录集成方案
- Spring 之 IOC/DI
- 99乘法表