刷题DAY3_数组

有序数组的平方 (977)

该题的暴力解法:每个元素平方再排序。
双指针法:

def multi(nums): #python

    i, j, k = 0, len(nums)-1, len(nums)-1
    result = [float('inf')] * len(nums)
    # 此处为定义一个长度为len(nums)的所有元素均为无穷的数组,也可以用numpy中np.zeros()
    while i <= j:
        if nums[i] * nums[i] < nums[j]*nums[j]:
            result[k] = nums[j]*nums[j]
            j -= 1 #右指针前移一位
        else:
            result[k] = nums[i] * nums[i]
            i += 1 #左指针后移一位
        k -= 1 #结果指针前移一位
    return result

if __name__ == "__main__":
    nums = [-7, -3, 2, 3, 11]
    print(multi(nums))

#include <iostream> //C++
#include <vector>
using namespace std;

vector<int> multi(vector <int> &nums) {
	int i = 0;
	int j = nums.size() - 1;
	int k = nums.size() - 1;
	vector<int> result(nums.size(), 0); //定义一个全0,长度为nums.size()的容器
	while (i <= j) {
		if (nums[i] * nums[i] < nums[j] * nums[j]) {
			result[k] = nums[j] * nums[j];
			j--;
			k--;
		}
		else {
			result[k] = nums[i] * nums[i];
			i++;
			k--;
		}
	}
	return result ;
}
int main() {
	vector <int>nums;
	int arr[5] = { -7, -3, 2, 3, 11 };
	int n = sizeof(arr) / sizeof(arr[0]);
	for (int i = 0;i < n;i++) {
		nums.push_back(arr[i]);
	}
	for (auto element : multi(nums)) { //输出vector容器中元素的方法之一
		std::cout << element << " ";

		//cout << multi(nums) << endl;
	}
}

注意事项和错误记录

  1. 该双指针法区别于快慢指针法
  2. 错误分析:no match for ‘operator<<‘无匹配的左移运算符
  3. C++中vector容器中元素输出(遍历)的5种方式
  4. vector result(nums.size(), 0); //定义一个全0,长度为nums.size()的容器 [C++]
  5. result = [float(‘inf’)] * len(nums); //定义一个长度为len(nums)的所有元素均为无穷的数组,也可以用numpy中np.zeros() [python]

个人刷题记录整理,欢迎随时纠错和讨论!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值