leetcode1-3 problem solution

leetcode 1-3 problem solution to a problem, implemented in C ++ and python

first question

Solving ideas
violence Solution
embedding two cycles: the first layer: I from 0 to n-2; second layer: from i + 1 to J n-1; Analyzing nums [i] + nums [j ] == target, If the establishment is the correct answer. Time complexity of O (n ^ 2)

** map Solution O (n * logn) **
the array exists inside a map, the key map is an array of values, the map value is the index of the array, so that only the original array to traverse to view a = target - nums [ i] values in the key is not in the map, if present, and map [a] and i are not equal, then the two values is the need to return the index.
Time complexity of O (n), the spatial complexity of O (n)

Code is as follows:
C ++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> myset;
        vector<int> results;
        for(auto tmp = nums.begin(); tmp<nums.end(); tmp++)
            myset[*tmp] = tmp - nums.begin();
        for(auto tmp = nums.begin(); tmp<nums.end(); tmp++)
        {
            if(myset.find(target - *tmp) != myset.end() && (*myset.find(target - *tmp)).second != (tmp-nums.begin()))
            {
                results.push_back(tmp-nums.begin());
                results.push_back(myset[target - *tmp]);
                break;
            }
        }
        return results;
    }
};

python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map = {}
        for i in range(len(nums)):
            if map.__contains__(target - nums[i]):
                return [map[target - nums[i]], i]
            map[nums[i]] = i

The second question

Solving ideas
left to right traverse the list in order to sum, for each location to generate a new node

Time complexity: O (max (len (l1 ), len2 (l2))
to consider boundary
processing into bits: carry represents a carry, when the last bit also carry, even if l1 and l2 are NULL, you also need generate a new node

Code is as follows:
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) {
        ListNode *head = new ListNode(0); //建立观察节点
        ListNode *temp = head;
        
        int carry = 0; //保留进位
        int sum = 0;
        
        while(l1 || l2)
        {
            if(l1 && l2) //两个链表都非空
            {
                sum = l1->val + l2->val + carry;
                l1 = l1->next;
                l2 = l2->next;
            }
            else if(l1)
            {
                sum = l1->val + carry;
                l1 = l1->next;
            }
            else
            {
                sum = l2->val + carry;
                l2 = l2->next;
            }
            //求出和和进位 添加到新的链表
            carry = sum/10;
            sum = sum % 10;
            head->next = new ListNode(sum);
            head = head->next;
            if((l1 == NULL || l2 == NULL) && carry == 0)
            {
                head->next = l1 ? l1 : l2; //将非空链表的剩余节点添加到新联表中
                return temp->next;
            }
        }
        if (carry) //如果最后以为还有进位
        {
            head->next = new ListNode(carry);
        }
        //head->next->next = NULL;
        
        return temp->next;
    }
};

python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        p=result=ListNode (-1)
        temp=0
        while l1 and l2:#当l1和l2属于同长度部分
            sum=l1.val+l2.val+temp
            temp=int(sum/10)
            ptemp=ListNode(sum%10)
            p.next=ptemp
            
            p=p.next
            l1=l1.next
            l2=l2.next
            
        temp1=l1 or l2
            
        while temp1:#当l1和l2属于不同长度部分
            sum=temp1.val+temp
            temp=int(sum/10)
            ptemp=ListNode(sum%10)
            p.next=ptemp
            
            p=p.next
            temp1=temp1.next
        if temp:
            p.next=ListNode(temp)
        return result.next

The third question

If you give an example of "abcabcbb", allows you to manually find substring no repeat characters, how to find? A character traversing a character, such as a, b, c, and then there was a a, then the time should remove the first occurrence of a, then continue to the next, there was a b, then it should be removed first appearance , b, and so on, eventually found the longest length of 3. So, we appeared before the need to record character, record There are many ways, the most common is to count the number of characters appear, but the position of the character appears This question is very important, so that we can use to build character and its HashMap the mapping between the position appears. Further consideration, since the character will be repeated, in the end is to save all occurrences, or is it only records a position? We derive the manual method before actually maintains a sliding window are no repeating characters in the window, we need to expand the size of the window as possible. Since the window kept sliding to the right, so we only care about the position of the last occurrence of each character, and establish a mapping. The position of the right border of the window is the visiting to the character, in order to obtain the size of the window, we need a variable to point to the left of the left edge of the sliding window, so if the current traverse to the character never appeared, so direct for right border, if there before too, then two cases, within or out of the sliding window, if not sliding window, then right, the current character you can add to the mix, if so, you need to remove this in the sliding window the character has appeared, the method does not remove the need to traverse the left border left one bit to the right to find, because we have the HashMap save the location of the last occurrence of repeated characters, so a direct move left pointer on it. We maintain a result res, each with a window size appeared to update the results res, you can get the final result.

Code
C ++

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
       vector<int> m(256,-1);
        int res = 0, left = -1;
        for(int i = 0; i < s.size(); ++i)
        {
            left = max(left, m[s[i]]);
            m[s[i]] = i;
            res = max(res, i - left);
        }
        return res;
    }
};

python

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        res = 0
        List = []
        for i in s:
            if i not in List:
                List.append(i)
                res = max(res, len(List))
            else:
                index = List.index(i)
                List.append(i)
                List = List[index+1:]
        return res

Guess you like

Origin www.cnblogs.com/chengdongliang/p/11949151.html