快手19春招实习笔试(Leetcode 136 && Leetcode 665)
快手3.30晚笔试编程题,比较简单,两道都是Leetcode原题。
1.Leetcode 136 Single Number
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
题解:
题目链接:https://leetcode.com/problems/single-number/
题意:给你一个数组,数组中的元素都是出现两次的,除了一个元素,请你找出这个元素。
思路:这道题的解法比较多。
-
最巧妙的方法是通过异或运算来解,时间复杂度为 O ( n ) O(n) O(n) ,空间复杂度为 O ( 1 ) O(1) O(1);一个数和0异或为它本身,和自身异或的结果为0。
a ⊕ 0 = a a ⊕ 0 = a a⊕0=a
a ⊕ a = 0 a ⊕ a = 0 a⊕a=0
a ⊕ b ⊕ a = ( a ⊕ a ) ⊕ b = 0 ⊕ b = b a⊕b⊕a=(a⊕a)⊕b=0⊕b=b a⊕b⊕a=(a⊕a)⊕b=0⊕b=b -
还可以通过
Hashtable
来解,记录每个元素出现的次数;时间复杂度为 O ( n ) O(n) O(n) ,空间复杂度为 O ( n ) O(n) O(n) -
还可以用
set
进行去重,在将数组的和相减。
代码:
异或:
class Solution{
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(int i=0; i<nums.size(); i++){
res ^= nums[i];
}
return res;
}
};
利用字典记录:
# 利用字典存储
def singleNumber1(self, nums):
dict = {}
for num in nums:
dict[num] = dict.get(num, 0) + 1
for key, value in dict.items():
if value == 1:
return key
利用set去重:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 利用集合去重
return sum(set(nums))*2 - sum(nums)
2.Leetcode 665 Non-decreasing Array
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can’t get a non-decreasing array by modify at most one element.
Note: The n belongs to [1, 10,000].
题解:
题目链接:https://leetcode.com/problems/non-decreasing-array/
题意:判断一个数组是否是非减少数组,最多只能修改数组中的一个元素,把数组变成非减少数组,非减少数组的定义为:array[i] <= array[i + 1]
,除第一个元素和最后一个元素外,数组中每个元素都小于其后一个元素。
思路:直接判断array[i]
和array[i+1]
的大小关系,判读是否需要修改元素。因为只能修改一次元素,修改的元素由array[i-1]
和array[i+1]
的大小关系确定。如果array[i-1]
大于array[i+1]
,就将array[i+1]
修改为array[i]
;如果array[i-1]
小于array[i+1]
,就将array[i]
修改为array[i+1]
。超过一次修改,直接return false
。
代码:
class Solution{
public:
bool checkPossibility(vector<int>& nums){
int len = nums.size(), count = 0;
for(int i=0; i < len-1; i++){
if(nums[i] > nums[i+1]){
count++;
if(count > 1){
return false;
}
if(i > 0 && nums[i+1] < nums[i-1]){
nums[i+1] = nums[i];
}
else{
nums[i] = nums[i+1];
}
}
}
return true;
}
};
更多代码可以查看github。