This commit is contained in:
krahets
2024-04-07 03:05:15 +08:00
parent aea68142f8
commit d8caf02e9e
21 changed files with 118 additions and 101 deletions

View File

@ -709,8 +709,8 @@ comments: true
### 删除索引 index 处的元素 ###
def remove(nums, index)
# 把索引 index 之后的所有元素向前移动一位
for i in index...nums.length
nums[i] = nums[i + 1] || 0
for i in index...(nums.length - 1)
nums[i] = nums[i + 1]
end
end
```
@ -949,7 +949,7 @@ comments: true
count += nums[i]
}
// 直接遍历数组元素
for (j: Int in nums) {
for (j in nums) {
count += j
}
}
@ -1155,7 +1155,8 @@ comments: true
/* 在数组中查找指定元素 */
fun find(nums: IntArray, target: Int): Int {
for (i in nums.indices) {
if (nums[i] == target) return i
if (nums[i] == target)
return i
}
return -1
}

View File

@ -597,7 +597,7 @@ comments: true
=== "Kotlin"
```kotlin title="linked_list.kt"
/* 在链表的节点 n0 之后插入节点p */
/* 在链表的节点 n0 之后插入节点 P */
fun insert(n0: ListNode?, p: ListNode?) {
val n1 = n0?.next
p?.next = n1
@ -811,9 +811,11 @@ comments: true
```kotlin title="linked_list.kt"
/* 删除链表的节点 n0 之后的首个节点 */
fun remove(n0: ListNode?) {
val p = n0?.next
if (n0?.next == null)
return
val p = n0.next
val n1 = p?.next
n0?.next = n1
n0.next = n1
}
```
@ -1018,7 +1020,9 @@ comments: true
fun access(head: ListNode?, index: Int): ListNode? {
var h = head
for (i in 0..<index) {
h = h?.next
if (h == null)
return null
h = h.next
}
return h
}
@ -1249,7 +1253,8 @@ comments: true
var index = 0
var h = head
while (h != null) {
if (h.value == target) return index
if (h.value == target)
return index
h = h.next
index++
}

View File

@ -2181,11 +2181,11 @@ comments: true
/* 列表类 */
class MyList {
private var arr: IntArray = intArrayOf() // 数组(存储列表元素)
private var capacity = 10 // 列表容量
private var size = 0 // 列表长度(当前元素数量)
private var extendRatio = 2 // 每次列表扩容的倍数
private var capacity: Int = 10 // 列表容量
private var size: Int = 0 // 列表长度(当前元素数量)
private var extendRatio: Int = 2 // 每次列表扩容的倍数
/* 构造函数 */
/* 构造方法 */
init {
arr = IntArray(capacity)
}
@ -2204,7 +2204,7 @@ comments: true
fun get(index: Int): Int {
// 索引如果越界,则抛出异常,下同
if (index < 0 || index >= size)
throw IndexOutOfBoundsException()
throw IndexOutOfBoundsException("索引越界")
return arr[index]
}
@ -2244,7 +2244,7 @@ comments: true
fun remove(index: Int): Int {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("索引越界")
val num: Int = arr[index]
val num = arr[index]
// 将将索引 index 之后的元素都向前移动一位
for (j in index..<size - 1)
arr[j] = arr[j + 1]