📣 Back to School开学季 - VIP通行证5折优惠!蓝莓、Offer多多同步优惠
查看: 1637| 回复: 3
跳转到指定楼层
上一主题 下一主题
收起左侧

LeetCode Microsoft Python Algorithm 面试真题 (Arrays and Strings)

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 Sarahxy07 于 2021-1-19 16:11 编辑
. Χ
先小小吐槽一下Microsoft的HR,1月初通过了Data Scientist第一轮的Python Technical Screen,HR还让我book了一天off,参加1月22号温哥华的interview day,上周五居然群发邮件把我拒了,理由是人数多出来了,真是太坑了,害我认认真真准备了快两个星期了。

现在分享一下LeetCode上Microsoft Python Algorithm的真题吧,先分享arrays and strings这部分。希望能够多多涨大米,可以让我体验一把飞一样的感觉。

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

You can return the answer in any order.

Solution:class Solution:   
    def twoSum(self, nums: List[int], target: int) -> List[int]:

        for i in range(len(nums)):
            if target - nums in nums[i+1:]:
        return [i, nums[i+1:].index(target - nums)+i+1]

2. Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.. .и

Note: For the purpose of this problem, we define empty string as valid palindrome.

Solution. 1point3acres
class Solution:
    def isPalindrome(self, s: str) -> bool:

        l, r = 0, len(s)-1

        while l < r:
. From 1point 3acres bbs
            if s[l].isalnum() and s[r].isalnum():
                if s[l].lower() != s[r].lower():. 1point 3 acres
                    return False
                l += 1
                r -= 1. From 1point 3acres bbs
            else:.--
                if not s[l].isalnum():
                    l += 1
                if not s[r].isalnum():
                    r -= 1
. check 1point3acres for more.
        return True

3. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
.--
The algorithm for myAtoi(string s) is as follows:
. 1point3acres.com
Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored..
Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
Return the integer as the final result.
Note:. Χ

Only the space character ' ' is considered a whitespace character.
Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
.
Solution. .и
class Solution:. 1point3acres
    def myAtoi(self, s: str) -> int:

        s = s.lstrip()

        if not s:.
            return 0

        res = ''

        if s[0] in ['+', '-']:
            res += s[0]
            s = s[1:]

        for i in range(len(s)):
            if s.isdigit():
                res += s
.--            else:
                break

        if res == '' or res == '+' or res == '-':. .и
            return 0
        elif int(res) > 2**31 - 1:
            return 2**31 - 1. 1point3acres.com
        elif int(res) < -2**31:. .и
            return -2**31
        else:. check 1point3acres for more.
            return int(res). From 1point 3acres bbs

4. Write a function that reverses a string. The input string is given as an array of characters char[]..google  и

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
-baidu 1point3acres
You may assume all the characters consist of printable ascii characters.
. .и
Solution
class Solution:. ----
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
.google  и
        l, r = 0, len(s)-1

        while l < r:
            s[l], s[r] = s[r], s[l]. Waral dи,
            l += 1
            r -= 1

5. Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Solution.
class Solution:
    def reverseWords(self, s: str) -> str:

        s = s.split()


        l, r = 0, len(s) - 1 ..

        while l < r:
            s[l], s[r] = s[r], s[l]
            l += 1
            r -= 1
.--
        return ' '.join(s)

6. Given an input string , reverse the string word by word.

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]-baidu 1point3acres
Note:

A word is defined as a sequence of non-space characters..
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?

Solution
class Solution:
    def reverseWords(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """

        def reverse(s, l, r):
            while l < r:
                s[l], s[r] = s[r], s[l]
                l += 1
                r -= 1
.--. check 1point3acres for more.
        def reverse_each_word(s):
            n = len(s)
            start = end = 0
            while start < n:
                while end < n and s[end] != ' ':
                    end += 1
                reverse(s, start, end-1)
                start = end+1
                end += 1
. 1point3acres
        reverse(s, 0, len(s)-1)
        reverse_each_word(s)

7. Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. ..

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

Solution
class Solution:
    def isValid(self, s: str) -> bool:
-baidu 1point3acres
        stack = []

        maps = {'(':')', '[':']', '{':'}'}

        for i in range(len(s)):
            if s in maps:
                stack.append(s)
            else:
                if not stack or maps[stack[-1]] != s:
                    return False
                else:
. .и                    stack.pop()

        return not stack

8. Given a string s, return the longest palindromic substring in s..google  и

Solution:
class Solution:
    def longestPalindrome(self, s: str) -> str:

        def longestPalindromeCenteredAt(i, j):
            while i >= 0 and j < len(s) and s == s[j]:
                i -= 1
                j += 1
            return s[i+1:j]

        res = ''. 1point 3 acres

        for i in range(len(s)):. 1point3acres
            newResult = longestPalindromeCenteredAt(i, i)
            if len(newResult) > len(res):
                res = newResult
            if i+1 < len(s):
                newResult = longestPalindromeCenteredAt(i, i+1)
                if len(newResult) > len(res):. 1point 3acres
                    res = newResult. .и

        return res

9. Given an array of strings strs, group the anagrams together. You can return the answer in any order.
.1point3acres
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Solution
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:

        res = {}

        for i in range(len(strs)):. .и
            temp = tuple(sorted(strs))
            if temp in res:
                res[temp].append(strs)
            else:
                res[temp] = [strs]

        return res.values()

10. Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Solution
class Solution:
    def trap(self, height: List[int]) -> int:. Χ

        leftmost = rightmost = 0
        left, right = 0, len(height)-1

        res = 0

        while left < right:
            leftmost = max(leftmost, height[left])
            rightmost = max(rightmost, height[right]). 1point3acres.com
            if leftmost < rightmost:
                res += leftmost - height[left]
                left += 1
            else:-baidu 1point3acres
                res += rightmost - height[right]. 1point 3 acres
                right -= 1

        return res

11. Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place..1point3acres

Follow up:
. check 1point3acres for more.
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution. ..
Could you devise a constant space solution?

Solution:
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead..google  и
        """

        m, n = len(matrix), len(matrix[0])

        r, c = set(), set()
. Waral dи,
        for i in range(m):
            for j in range(n):
                if matrix[j] == 0:
                    r.add(i). Waral dи,
                    c.add(j)

        for i in range(m):
            for j in range(n):. check 1point3acres for more.
                if i in r or j in c:
                    matrix[j] = 0
. 1point 3 acres
12. You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Solution:
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """

        n = len(matrix)
.1point3acres
        for i in range(n):. 1point 3 acres
            for j in range(i, n):
                matrix[j], matrix[j] = matrix[j], matrix[j]

        for k in range(n):
            matrix[k].reverse()

13. Given an m x n matrix, return all elements of the matrix in spiral order.
. check 1point3acres for more.
Solution:
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
. From 1point 3acres bbs
        R, C = len(matrix), len(matrix[0]). check 1point3acres for more.
        seen = [[False]*C for _ in range(R)]
        dr = [0, 1, 0, -1]. 1point3acres
        dc = [1, 0, -1, 0]
        r=c=di=0
        res=[]

        for _ in range(R*C):
            res.append(matrix[r][c]). ----
            seen[r][c] = True

            rr, cc = r + dr[di], c + dc[di]

            if 0<= rr < R and 0 <= cc < C and not seen[rr][cc]:
                r, c = rr, cc. 1point3acres
            else:
                di = (di+1) % 4. Χ
                r, c = r + dr[di], c + dc[di]

        return res
.1point3acres
.--


.

评分

参与人数 5大米 +22 收起 理由
kellyiwork + 1 赞一个
ppline + 2 给你点个赞!
ZYYYZ + 3 很有用的信息!
pikado + 15 欢迎分享你知道的情况,会给更多积分奖励!
GreenHill + 1 谢谢分享!

查看全部评分


上一篇:文科转data science !!! 求助!!data science certificate
下一篇:应该先找project做还是先刷题呢?
🔗
ZYYYZ 2021-1-20 15:27:56 | 只看该作者
全局:
大温巨硬这么坑的吗。。。安慰下LZ

这个岗位HR在领英上找我,我申请之后就没消息了,害hhh
回复

使用道具 举报

🔗
 楼主| Sarahxy07 2021-1-21 02:23:17 | 只看该作者
全局:
HR的名字是不是J开头的?也是在Linkedin上找我的,让我大年夜填了申请表,第二天又做了online test,后来告诉我过了,他们还在排时间,让我先请好假。
回复

使用道具 举报

🔗
ZYYYZ 2021-1-21 05:22:52 | 只看该作者
全局:
Sarahxy07 发表于 2021-1-21 02:23
HR的名字是不是J开头的?也是在Linkedin上找我的,让我大年夜填了申请表,第二天又做了online test,后来告 ...

不是的哈,是A开头的
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表