two sum
来源:互联网 发布:js li默认选中样式 编辑:程序博客网 时间:2024/06/13 11:48
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解决方案:O(n log n)。 将索引和元素包装在一个类中,并以升序排序。 做两个index的和并比较。
一个替代的解决方案是使用一个O(n)解决方案的散列 - 对于每个元素e检查元素(target-e)
已经在hashset中找到,如果是,则返回其索引,否则将其添加到哈希集并继续。
public class TwoSum { class NumIndex { int i, e; NumIndex(int i, int e){ this.i = i; this.e = e; } } public static void main(String[] args) { int[] nums = {3, 2, 4}; int[] ans = new TwoSum().twoSum(nums, 6); for (int i : ans) System.out.println(i); } public int[] twoSum(int[] nums, int target) { List<NumIndex> list = new ArrayList<>(); for(int i = 0; i < nums.length; i ++){ NumIndex n = new NumIndex(i, nums[i]); list.add(n); } list.sort((o1, o2) -> Integer.compare(o1.e, o2.e)); int[] ans = new int[2]; for(int i = 0, j = nums.length - 1; i < j; ){ NumIndex numi = list.get(i); NumIndex numj = list.get(j); int sum = numi.e + numj.e; if(sum == target){ ans[0] = numi.i; ans[1] = numj.i; return ans; } else if(sum > target){ j --; } else i++; } return ans; }}
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
public class TwoSumII{ public static void main(String[] args) throws Exception { int[] nums = {2, 7, 11, 15}; int[] result = new TwoSumII().twoSum(nums, 23); for (int i : result) System.out.println(i); } public int[] twoSum(int[] numbers, int target) { int i = 0, j = numbers.length - 1; while(i < j) { int x = (numbers[i] + numbers[j]); if(x == target) { int[] result = new int[2]; result[0] = i + 1; result[1] = j + 1; return result; } else if(x < target) i++; else j--; } return new int[2]; }}
- 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
- java 快速排序
- 深度图转伪色彩图
- java IO笔记(CharArrayReader/CharArrayWriter)
- 五种经典排序算法的实现(冒泡、归并、快排、堆排序、希尔)
- BZOJ 4059: [Cerc2012]Non-boring sequences 启发式合并
- two sum
- VUE axios 实现自定义下载功能
- 重写equlas,hashcode . 和比较类大小
- HDU-2795 Billboard(线段树)
- ASP.NET权限管理(二)
- studio快捷键(后面会在遇到的时候持续更新)
- Hello CSDN!
- linux shell 管道命令(pipe)使用及与shell重定向区别
- 设计模式