Array(陣列)是一種儲存多個相同類型值的資料結構。它可以在一個變數中存放多個值,並且每一個值都可以通過索引來訪問。索引通常是整數型別,它從 0 開始,依次增加。
以下是一些 Array 的例子:
let numbers = [1, 2, 3, 4, 5];
console.log(numbers); // [1, 2, 3, 4, 5]
let fruits = ["apple", "banana", "orange", "grape"];
console.log(fruits); // ["apple", "banana", "orange", "grape"]
let bools = [true, false, true];
console.log(bools); // [true, false, true]
let users = [
{ name: "Amy", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Carl", age: 28 }
];
console.log(users); // [{name: "Amy", age: 25}, {name: "Bob", age: 30}, {name: "Carl", age: 28}]
需要注意的是,Array 有一些屬性和方法,可以對其中的值進行操作,比如 length
屬性可以返回陣列的大小,push
方法可以在陣列末尾添加一個元素,splice
方法可以在指定位置插入或刪除元素等。
以下是Array的重點:
定義:Array是一種數據結構,它由相同類型的元素組成,並存儲在相鄰的內存位置上。
屬性:Array具有下面幾個屬性:
總結起來,Array 是一種非常基礎且常用的數據結構,它非常適用於儲存一系列具有相同類型的數據,並提供了高效的隨機訪問、修改、刪除和新增元素的操作。
答案:
def two_sum(arr, target):
res = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == target:
res.append([arr[i], arr[j]])
return res
arr = [2, 7, 11, 15]
target = 9
print(two_sum(arr, target))
答案:
def largest_num(arr):
arr = list(map(str, arr))
arr.sort(key=lambda x: x*3, reverse=True)
return ''.join(arr)
arr = [3, 30, 34, 5, 9]
print(largest_num(arr))
答案:
def longest_consecutive_sequence(arr):
if not arr:
return 0
nums = set(arr)
max_len = 0
for num in nums:
if num-1 not in nums:
curr_num = num
curr_len = 1
while curr_num+1 in nums:
curr_num += 1
curr_len += 1
max_len = max(max_len, curr_len)
return max_len
arr = [100, 4, 200, 1, 3, 2]
print(longest_consecutive_sequence(arr))
答案:
def smallest_missing_positive_num(arr):
if not arr:
return 1
for i in range(len(arr)):
while 0 < arr[i] <= len(arr) and arr[i] != arr[arr[i]-1]:
arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1]
for i in range(len(arr)):
if arr[i] != i+1:
return i+1
return len(arr) + 1
arr = [1, 2, 0]
print(smallest_missing_positive_num(arr))
答案:
def interval_intersection(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
res = []
curr_start, curr_end = intervals[0]
for interval in intervals[1:]:
if interval[0] <= curr_end:
curr_start = max(curr_start, interval[0])
curr_end = min(curr_end, interval[1])
else:
res.append([curr_start, curr_end])
curr_start, curr_end = interval[0], interval[1]
res.append([curr_start, curr_end])
return res
intervals = [[1, 3], [2, 6], [5, 8], [7, 9]]
print(interval_intersection(intervals))