遍历数组,j = nums[i] - 1 作为索引,nums[j] 增加 n,这样会保留原数组的信息,即 nums[j] % n 能还原数组。再次遍历数组,如果 nums[i] 小于等于 n,索引 i + 1 就是数组中消失的数字。
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
n = len(nums)
for e in nums:
j = (e - 1) % n
nums[j] += n
return [i + 1 for i, x in enumerate(nums) if x <= n]
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++){
int x = Math.abs(nums[i]) - 1;
if (nums[x] > 0) nums[x] *= -1;
}
List<Integer> res = new ArrayList<>();
for (int i = 0; i < n; i++){
if (nums[i] > 0) res.add(i + 1);
}
return res;
}
}
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = []
for i in range(numRows):
tmp = [1] * (i + 1)
for j in range(1, i):
tmp[j] = res[-1][j-1] + res[-1][j]
res.append(tmp)
return res
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> tri = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> row = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) row.add(1);
else row.add(tri.get(i-1).get(j-1) + tri.get(i-1).get(j));
}
tri.add(row);
}
return tri;
}
}
class Solution {
public List<List<Integer>> generate(int numRows) {
List<Integer> row = new ArrayList<>();
List<List<Integer>> tri = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
row.add(0, 1);
for (int j = 1; j < i; j++) {
row.set(j, row.get(j) + row.get(j + 1));
}
tri.add(new ArrayList<Integer>(row));
}
return tri;
}
}
妙在 row.add(0, 1); 和 tri.add(new ArrayList(row));
每一行数据生成都用同一个 ArrayList 对象储存,注意 add 和 set 的妙用,使得一行中 ArrayList 既存储了上一行数据,又有当前行的新数据,然后 tri.add(new ArrayList(row)); 用 row 构造初始化新的对象存入杨辉三角。
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> tri = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
Integer[] row = new Integer[i + 1];
Arrays.fill(row, 1);
for (int j = 1; j < i; j++) {
row[j] = tri.get(i-1).get(j-1) + tri.get(i-1).get(j);
}
tri.add(Arrays.asList(row));
}
return tri;
}
}
基础知识
Java ArrayList
|