import java.util.HashMap;
import java.util.Map;
/*遍历将补数存起来作为key,然后,如果这个数后面有与补数相等的数,则表示,找到罗*/
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexs = new int[2];
// 建立k-v ,一一对应的哈希表
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
if(hash.containsKey(nums[i])){
indexs[0] = i;
indexs[1] = hash.get(nums[i]);
return indexs;
}
// 将数据存入 key为补数 ,value为下标
hash.put(target-nums[i],i);
}
// // 双重循环 循环极限为(n^2-n)/2
// for(int i = 0; i < nums.length; i++){
// for(int j = nums.length - 1; j > i; j --){
// if(nums[i]+nums[j] == target){
// indexs[0] = i;
// indexs[1] = j;
// return indexs;
// }
// }
// }
return indexs;
}
}
public int[] twoSum(int[] numbers, int target) { int i = 0, j = numbers.length - 1; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum == target) { return new int[]{i + 1, j + 1}; } else if (sum < target) { i++; } else { j--; } } return null; }
-
双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。
1. 有序数组的 Two Sum
Leetcode :167. Two Sum II - Input array is sorted (Easy)
Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
题目描述:在有序数组中找出两个数,使它们的和为 target。
使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。
- 如果两个指针指向元素的和 sum == target,那么得到要求的结果;
- 如果 sum > target,移动较大的元素,使 sum 变小一些;
- 如果 sum < target,移动较小的元素,使 sum 变大一些。
2、给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
使用递归
public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1==null)//这里使用l1.equels(null)会报空指针异常,一个null表示还没有分配内存,所以不能调用object里面的方法 return l2; if(l2==null) return l1; int val = l1.val+l2.val; ListNode sum = new ListNode(0); sum.val = val%10; int carry = val/10; sum.next = addTwoNumbers(l1.next,l2.next); if(carry>0){ sum.next= addTwoNumbers(sum.next,new ListNode(carry)); } return sum; } public static void main(String args[]) { ListNode a = new ListNode(2); ListNode aa = new ListNode(4); ListNode aaa = new ListNode(3); a.next = aa; aa.next = aaa; ListNode a1 = new ListNode(5); ListNode aa1 = new ListNode(6); ListNode aaa1 = new ListNode(4); a1.next = aa1; aa1.next = aaa1; ListNode re = addTwoNumbers(a,a1); while(re!=null){//这里使用re.equels(null)会报空指针异常 System.out.println(re.val); re = re.next; } }
非递归
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode(0);
ListNode cursor = root;
int carry = 0;
while(l1 != null || l2 != null || carry != 0) {
int l1Val = l1 != null ? l1.val : 0;
int l2Val = l2 != null ? l2.val : 0;
int sumVal = l1Val + l2Val + carry;
carry = sumVal / 10;
ListNode sumNode = new ListNode(sumVal % 10);
cursor.next = sumNode;
cursor = sumNode;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
return root.next;
}
}