前言

  近日思想较为纠结,也不想看书什么的,所以就没事干看了看LeetCode上面的题目。未来如何发展很迷茫呀,还是忙好当下应该做的事情!

Two Sum [easy]

题面

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题解

  该题目的题意是从所给定的数组中挑选哪两个数值相加可以得到我们想要的target,然后输出两个数值所在的索引。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic={}
for i,val in enumerate(nums):
if(target-val) in dic:
return [dic[target-val],i]
dic[val]=i

Add Two numbers [Medium]

题面

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题解

  可以看出来,两个链状链表表示的是两个多位数,例如样例中的input就是代表了两个数值,分别是342与465.可以看出该链表中,代表的位置越深代表的数字位数越高,如Input中所代表的3为百分位,2为个位。
  我的想法是将两个数组先分别生成两个数,然后将其相加,之后再将解生成为一个链表即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ans=[]
tmp=0
ll1=0
ll2=0
while(l1):
ll1+=l1.val*(10**tmp)
l1=l1.next
tmp+=1
tmp=0
while(l2):
ll2+=l2.val*(10**tmp)
l2=l2.next
tmp+=1
tmp=ll1+ll2
while(tmp//10 or tmp):
ans.append(tmp%10)
tmp=tmp//10
if(len(ans)==0):
ans.append(0)
return ans

Longest Substring Without Repeating Characters

题面

Given a string, find the length of the longest substring without repeating characters.

Example

Example 1:

1
2
3
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

1
2
3
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

1
2
3
4
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

题解

  本题应该注意的是他所需要的是最长不重复子串的长度,而不是最长不重复子序列的长度。两者有什么区别呢?类似 Example 3 中所示如果是最长不重复子序列,那么解应该是pwke,但是子串必须是连续的,因此最长的只有wke
  首先我们需要一个dict的usedChar,用它来保存我们现在已经读到的所有字符以及最近的距离。用start保存当前保存的最长不重复子串的开始地点,然后遍历字符串,若该字符已出现且start小于该字符之前的位置;否则就重新规划最长长度,也就是现在的长度和之前的最长长度的最大值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
start = maxLength = 0
usedChar = {}

for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i - start + 1)

usedChar[s[i]] = i

return maxLength

后记

  看看题什么的主要就是调整一下自己的心情,因为真的不知道未来该如何发展,太纠结了,对未来充满了迷茫呀!不过就算是再迷茫还是要做好当前的事情。