1.两数之和
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
public static int[] twoSum(int[] nums, int target) { for(int a = 0 ;a < nums.length; a++) { for(int b = a+1 ;b < nums.length; b++) { int num = nums[a]+nums[b]; if(num == target) { return new int[] { a, b }; } } } //表明向方法传递了一个不合法或不正确的参数 throw new IllegalArgumentException("No two sum solution"); } public static void main(String[] args) { int[] nums = {2, 5, 5, 11}; int[] res = twoSum(nums,13); for (int i = 0; i < res.length; i++) { System.err.println("对应的值:"+nums[res[i]]+"对应标:"+res[i]); } }
2.两数想加
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x + y; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); } return dummyHead.next; } public static void main(String[] args) { //设置参数1 ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(3); //设置参数2 ListNode l2 = new ListNode(1); //调用参数 ListNode l3 = addTwoNumbers( l1, l2); //全部参数1 while (l1 != null) { System.out.print(l1.val); l1 = l1.next; if (l1 != null) { System.out.print("->"); } } System.out.println("//"); //全部参数2 while (l2 != null) { System.out.print(l2.val); l2 = l2.next; if (l2 != null) { System.out.print("->"); } } System.out.println("//"); //全部返回值 while (l3 != null) { System.out.print(l3.val); l3 = l3.next; if (l3 != null) { System.out.print("->"); } } }