mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-08 05:26:07 +00:00
feat: modify some Dart codes and add Dart code blocks to the docs (#543)
This commit is contained in:
@@ -6,9 +6,9 @@
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
/* 随机返回一个 数组元素 */
|
||||
/* 随机返回一个数组元素 */
|
||||
int randomAccess(List nums) {
|
||||
// 在区间[0,size) 中随机抽取一个数字
|
||||
// 在区间 [0, nums.length) 中随机抽取一个数字
|
||||
int randomIndex = Random().nextInt(nums.length);
|
||||
// 获取并返回随机元素
|
||||
int randomNum = nums[randomIndex];
|
||||
@@ -17,9 +17,8 @@ int randomAccess(List nums) {
|
||||
|
||||
/* 扩展数组长度 */
|
||||
List extend(List nums, int enlarge) {
|
||||
// 初始化一个扩展长度后的数组,元素初始值为0
|
||||
// 初始化一个扩展长度后的数组
|
||||
List<int> res = List.filled(nums.length + enlarge, 0);
|
||||
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
for (var i = 0; i < nums.length; i++) {
|
||||
res[i] = nums[i];
|
||||
@@ -30,7 +29,7 @@ List extend(List nums, int enlarge) {
|
||||
|
||||
/* 在数组的索引 index 处插入元素 num */
|
||||
void insert(List nums, int num, int index) {
|
||||
// 把索引index以及之后的所有元素向后移动一位
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
for (var i = nums.length - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
@@ -40,6 +39,7 @@ void insert(List nums, int num, int index) {
|
||||
|
||||
/* 删除索引 index 处元素 */
|
||||
void remove(List nums, int index) {
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for (var i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
@@ -56,7 +56,7 @@ void traverse(List nums) {
|
||||
for (var num in nums) {
|
||||
count++;
|
||||
}
|
||||
// 通过forEach方法遍历数组
|
||||
// 通过 forEach 方法遍历数组
|
||||
nums.forEach((element) {
|
||||
count++;
|
||||
});
|
||||
@@ -71,8 +71,8 @@ int find(List nums, int target) {
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化固定长度数组 */
|
||||
void main() {
|
||||
/* 初始化数组 */
|
||||
var arr = List.filled(5, 0);
|
||||
print('数组 arr = $arr');
|
||||
List nums = [1, 3, 2, 5, 4];
|
||||
@@ -100,6 +100,4 @@ int main() {
|
||||
/* 查找元素 */
|
||||
int index = find(nums, 3);
|
||||
print("在 nums 中查找元素 3 ,得到索引 = $index");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user