1.两数之和:‘
class Solution:def twoSum( nums, target):for i in nums:if target - i in nums:if i != target - i:return [nums.index(i), nums.index(target - i)]elif nums.count(i) > 1:index1 = nums.index(i)nums.remove(i)return [index1, nums.index(i) + 1]print(Solution.twoSum([1, 2, 4, 5], 6))
print(Solution.twoSum([3, 2, 4], 6))
print(Solution.twoSum([3, 3], 6))
class Solution2:def twoSum(nums: List[int], target: int) -> List[int]:dist={}for d,ind in enumerate(nums):dist[ind] = dfor i, j in enumerate(nums):f = dist.get(target - j)if f is not None and f != i:return [i, f]print(Solution2.twoSum([1, 2, 4, 5], 6))
print(Solution2.twoSum([3, 2, 4], 6))
print(Solution2.twoSum([3, 3], 6))
package addTwoNumbs;import java.util.HashMap;
import java.util.Map;public class Demo2 {public static int[] twoSum(int[] nums, int target) {Map<Integer, Integer> storeNum = new HashMap<Integer, Integer>();int[] result = new int[2];for (int i = 0; i < nums.length; i++) {int another = target - nums[i];Integer another1 = storeNum.get(another);if (null != another1) {result[0] = another1;result[1] = i;break;} else {storeNum.put(nums[i], i);}}return result;}public static void main(String[] args) {int[] a = new int[] { 4, 6, 13, 8, 7, 9 };Long start=System.currentTimeMillis();int[] b = twoSum(a, 20);for (int i = 0; i < 2; i++) {System.out.println(b[i]);}Long end=System.currentTimeMillis();System.out.println(end-start);}
}
2.两数相加:
class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = next
class Solution:def addTwoNumbers( l1: ListNode, l2: ListNode) -> ListNode:re = ListNode(0)r=recarry=0while(l1 or l2):x= l1.val if l1 else 0y= l2.val if l2 else 0s=carry+x+ycarry=s//10r.next=ListNode(s%10)r=r.nextif(l1!=None):l1=l1.nextif(l2!=None):l2=l2.nextif(carry>0):r.next=ListNode(1)return re.next
Definition for singly-linked list.public class ListNode {int val;ListNode next;ListNode(int x) { val = x; }}class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode result = new ListNode(0);add(result, l1, l2, 0);return result;}private void add(ListNode result, ListNode l1, ListNode l2, int carry) {//出口if (l1 == null && l2 == null && carry == 0) return;if (l1 == null) l1 = new ListNode(0);if (l2 == null) l2 = new ListNode(0);int num = l1.val + l2.val + carry;carry = num / 10;result.val = num % 10;//如果一直递归的话,最后会多出一个节点,所以需要再这里再加一个判断//如果满足条件就停止递归if (l1.next == null && l2.next == null && carry == 0) return;//递归result.next = new ListNode(0);add(result.next, l1.next, l2.next, carry);}
}