【leetcode刷题笔记】链表,数组
两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i< nums.length; i ++){
for(int j = i+1; j < nums.length; j ++){
if(nums[i] + nums[j] == target){
return new int[] {i, j};
}
}
}
return new int [] {0,0};
}
}
两数相加
/**
* 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 r = new ListNode(0);
ListNode p1 = l1, p2 = l2, c = r;
while(p1 != null || p2 != null){
if(c.next == null) c.next = new ListNode(0);
c = c.next;
int sum = c.val
+ ((p1 != null) ? p1.val : 0)
+ ((p2 != null) ? p2.val : 0);
c.val = sum % 10;
int carry = sum / 10;
if(carry > 0){
c.next = new ListNode(carry);
}
if(p1 != null)p1 = p1.next;
if(p2 != null)p2 = p2.next;
}
return r.next;
}
}
下面的python能跑过但是提交后用时n/a?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def listNode2Number(self, l, d = 1):
n = l.val * d
if l.next != None:
n += self.listNode2Number(l.next, d * 10)
return n
def number2ListNode(self, n, l = ListNode(0)):
l.val = n % 10
if n > 10:
l.next = self.number2ListNode(int(n / 10), ListNode(0))
return l
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
return self.number2ListNode(self.listNode2Number(l1) + self.listNode2Number(l2))
子序列宽度之和
标准答案有些奇怪?
- 因为没有考虑重复元素不构成不同的子序列,比如:
[2,3,3,4] = [2, 4], [2,3,4], [2,3,3,4] 用这种解法就多算了一个子序列,变成[2, 4], [2,3,4], [2,3,4], [2,3,3,4] 。 - mod了太多次,题目只说返回结果的模。anyway, 这是我的解法:
class Solution {
public int sumSubseqWidths(int[] A) {
int MOD = 1_000_000_007;
int sum = 0;
Arrays.sort(A);
for(int i = 0; i < A.length; i ++){
for(int j = i+1; j < A.length; j ++){
sum += (A[j] - A[i]) * Math.pow(2, j - i - 1);
}
}
return sum % MOD;
}
}