1.两数之和
(1)题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是数组中同一个元素不能使用两遍。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
(2)python代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
find_num=target-nums[i]
if find_num in nums[i+1:]:
return [i,nums.index(target-nums[i],i+1)]
else:
pass
结果:
(3)优化方案-python代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap={}
for i,num in enumerate(nums):
hashmap[num] = i
for j,num_j in enumerate(nums):
k = hashmap.get(target - num_j)
if k is not None and j!=k:
return [j,k]
结果:
2. 0~n-1中缺失的数字
(1) 题目
一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
示例 1:
输入: [0,1,3]
输出: 2
示例 2:
输入: [0,1,2,3,4,5,6,7,9]
输出: 8
(2) python代码实现
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
j = 0
for i in range(len(nums)):
if j==nums[i]:
j+=1
else:
return j
return j
(3) C++代码实现
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int sum_all = 0;
for(int i = 0; i < n; i ++)
sum_all += nums[i];
return n*(n + 1)/2 - sum_all;
}
};
- 转置矩阵(867)
(1)题目
矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
示例 1:
输入:[[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
输入:[[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
(2)python代码
class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
array_0 = len(A)
array_1 = len(A[0])
new_A = [[None] * array_0 for k in range(array_1)]
for i, row in enumerate(A):
for j, val in enumerate(row):
new_A[j][i] = val
return new_A
(3)C++实现代码
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& A) {
vector<vector<int>> res(cow);
int row = A.size();
int cow = A[0].size();
for (int i = 0; i < row; ++i) {
for (int j = 0; j < cow; ++j)
res[j].emplace_back(A[i][j]);
}
return res;
}
};