首页 > 其他分享 >day2-array-part02-7.4

day2-array-part02-7.4

时间:2024-07-09 15:28:19浏览次数:11  
标签:count mut used nums part02 day2 result array Rust

task for today

1. 977.有序数组的平方 

2, 209.长度最小的子数组 

3. 59.螺旋矩阵II

---------------------------------------------

1. 977.有序数组的平方 

- 暴力法

raise each element in the array to the power of 2, and then sort them in ascending order.

it's worth noting that in python the nums.sort() function is allowed to be used.

As for Rust, because the nums given is not mutable, a new mutable vector should be defined "let mut ans = vec![0;l];" to store the outcome of rasing each element in nums to the power of 2. Besides, the ans.sort() is allowed to use in Rust.

Meanwhile, in GoLang, the nums' elements can be changed, just like in python, what needs to be paid attention to is, the corresponding function for sorting in GoLang is sort.Ints(nums)

- 双指针

Based on the ascending order of nums, so the largest number should show up in either left side or right side. Then, two pointer can be set respectively start from two sides of nums, then compare whose value to the power of 2 is larger.

in python to set a new array, ans[float('inf')] * len(nums) can be used, the corresponding expression in GoLang and Rust is:

in Go: ans:=make([]int, len(nums))

in Rust: let mut ans = vec![0; nums.len()];

another thing worth noting is "nums[i]**2" which is usually used in python is not valid in Go and Rust

In Rust, there is a small issue when holding a negative number with usize type, i32 csn hold but this will need "as usize" when indexing an element in a vector in Rust.

And in rust, "and" is &&

2, 209.长度最小的子数组 

the essence for this practice is slide window, the right pointer go through the array to accumulate the sum, when the sum is greater or equal to the target, the left window will start to move forward. Two while loops are gonna be used to realize this function.

in python, a "min(a,b)" is used to find the less length, pay attention to the corresponding usage in Go and Rust.

In Go, there is no built-in min function, while in Rust, the min(a,b) is also valid

in Rust, "let mut result = i32::MAX" is used to facilitate the similar function with result = float('inf')

in Rust, normally let mut left = 0, left will be usize type, which can be directlty used to index within a vector, but other function, it should be converted to i32 with "as i32" 

3. 59.螺旋矩阵II

注意循环不变量,左闭右开这里选择

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        if n == 1:
            return [[1]]
        # this is safer
        result = [[0] * n for _ in range(n)]
        startx, starty = 0, 0
        loop, mid = n // 2, n // 2
        count = 1
        for offset in range(1, loop + 1):
            for i in range(starty, n - offset):
                result[startx][i] = count
                count += 1
            for i in range(startx, n - offset):
                result[i][n - offset] = count
                count += 1
            for i in range(n - offset, starty, -1):
                result[n - offset][i] = count
                count += 1
            for i in range(n - offset, startx, -1):
                result[i][starty] = count
                count += 1
            
            startx += 1
            starty += 1
        
        # only odd number has a middle one
        if n % 2 != 0:
            result[mid][mid] = n**2

        return result

in Go, pay attention to "

res := make([][]int, n)

" this is used to initial the result matrix

while in Rust:"

let mut res = vec![vec![0; n as usize]; n as usize];
let (mut startX, mut startY, mut offset): (usize, usize, usize) = (0, 0, 1);

"

标签:count,mut,used,nums,part02,day2,result,array,Rust
From: https://blog.csdn.net/bbrruunnoo/article/details/140171196

相关文章

  • day4-linked list-part02-7.6
    taskfortoday1.24.两两交换链表中的节点2.19.删除链表的倒数第N个节点3.面试题02.07.链表相交4.142.环形链表II-------------------------------------------------------------------1.24.两两交换链表中的节点Inthispractice,payattentionto......
  • OC-NSArray的基本介绍
    NSArray是不可变的;存储不同类型的对象。这意味着一个NSArray可以同时包含NSString、NSNumber、NSDictionary等不同类型的对象。同时只能存储对象,不能直接存储基本数据类型(如int、float等)。如果需要存储基本数据类型,应该先将它们封装为相应的对象类型(如NSNumber或NSValue)。......
  • codeforces1849 D. Array Painting
    题目链接https://codeforces.com/problemset/problem/1849/D题意输入\(n(1\leqn\leq2e5)\)和长为\(n\)的数组\(a(0\leqa[i]\leq2)\)。最初,数组的每个元素都是蓝色的。有两种类型的操作:支付一枚硬币,选择一个蓝色元素,将其涂成红色。选择一个不等于\(0\)的红......
  • [LeetCode] 238. Product of Array Except Self
    坑真的很多,首先要处理全零reduce没有值typeerror的问题。classSolution:defproductExceptSelf(self,nums:List[int])->List[int]:total=reduce(mul,nums)ret=[]iftotal==0:try:total=reduce(mul,[......
  • [CISCN2019 华北赛区 Day2 Web1]Hack World
    进入题目输入数字1数字20对select空格unionor等等测试发现没有过滤select空格也被过滤注意不能单独测试用亦或运算1^0为真尝试0^if((ascii(substr((select(flag)from(flag)),1,1))=100),0,1)回显正常根据回显判断正误编写脚本爆破,由于该网站请求太快会报429......
  • [CISCN2019 总决赛 Day2 Web1]Easyweb
    进入题目查看源码发现id参数可用sql注入脚本目录扫描发现robots.txt尝试fuzz爆破参数发现image.php.bak可用<?phpinclude"config.php";$id=isset($_GET["id"])?$_GET["id"]:"1";$path=isset($_GET["path"])?$_GET["path"]:"&......
  • return isPlainObject(res) || Array.isArray(res) ? observer(res, cb) : res; 这个
    这段代码主要是在实现一个深度观察者模式的部分逻辑,用于递归地处理对象和数组,以便在数据结构变化时触发回调。这里的关键是理解条件运算符和函数调用的执行顺序。让我们逐步分析:条件表达式的左侧:isPlainObject(res):这个函数检查res是否是一个纯对象(即普通的JavaScript对象......
  • HashTable,ArrayList,queue等常用方法
    HashTable,ArrayList,queue等常用方法HashMap是Java中非常常用的集合类,它存储键值对,并提供了一系列方便的方法来操作这些数据。以下是一些HashMap的常用方法:1.添加和获取元素:put(key,value):将指定的键值对添加到HashMap中。如果键已存在,则更新对应的值。get(ke......
  • Arrays,Object,String,StringBuffer和常用工具类汇总
    Arrays[数组操作方法:排序,查找,替换,转换,复制]排序将数组升序排序:Arrays.sort(数组);查找数组中想查找的数字的索引:Arrays.binarysearch(数组,想查找的数字(例如3));替换将数组中的元素全部用x替换:Arrays.fill(数组,x);Arrays.fill(数组,下标y,下标z,x);//y-z下标的元素替换为x......
  • 「杂题乱刷2」CF402D Upgrading Array
    题目链接CF402DUpgradingArray(luogu)CF402DUpgradingArray解题思路首先有一个很显然的结论,就是你一旦在第\(i\)个位置上做了一次操作后,那么你之后所有在第\(j(i\lej)\)个位置做的操作都无效了,因为此时前缀的公因数为\(1\)了。因此有个很显然的结论就是操作需要......