【学习任务】leetcode刷题

LeetCode

01 两数之和

若数组有序时可以达到O(n),题目没有保证数组有序
python:

1
2
3
4
5
6
7
8
9
10
11
12
class (object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
for x in range(0, n):
for y in range(x+1, n):
if(nums[x] + nums[y] == target):
return [x,y]

02 两数相加

C++:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int first = (l1->val + l2->val) % 10;
        int add = (l1->val + l2->val) / 10;
        ListNode *ans = new ListNode(first);
        l1 = l1->next; l2 = l2->next;
        ListNode *p = ans;
        while(l1 != NULL || l2 != NULL || add) {
            int val = 0;
            if(l1 != NULL) {
                val += l1->val;
                l1 = l1->next;
            }
            if(l2 != NULL) {
                val += l2->val;
                l2 = l2->next;
            }

            if(add) val += add;
            int a = val%10;add = val/10;
            ListNode *q = new ListNode(a); p->next=q; p=p->next;
        }
        return ans;
    }
};