2014-05-01 01:23
原题:
WAP to modify the array such that arr[I] = arr[arr[I]]. Do this in place i.e. with out using additional memory. example : if a = {2,3,1,0} o/p = a = {1,0,3,2} Note : The array contains 0 to n-1 integers.
题目:给定一个长度为n的数组,由0至n - 1的排列组成。请做这样的变换,arr[i] = arr[arr[i]]。要求就地完成,不用额外数组。
解法:当数据范围有明确限制时,能够通过压缩维度来节省空间。对于一个数对(x, y),如果x和y都属于[0, n - 1],那么x * n + y就能唯一表示这个数对了。因此,可以先把变换后的结果存在高位上,然后再把高位的数通过除法移动到低位。算法是线性的,能够就地完成。
代码:
1 // http://www.careercup.com/question?id=4909367207919616 2 #include <cstdio> 3 #include <vector> 4 using namespace std; 5 6 void displaceInPlace(vector<int> &v) 7 { 8 int i; 9 int n; 10 11 // all elements in the array has value between 0 and n - 1. 12 n = (int)v.size(); 13 for (i = 0; i < n; ++i) { 14 v[i] = v[v[i]] % n * n + v[i]; 15 } 16 for (i = 0; i < n; ++i) { 17 v[i] = v[i] / n; 18 } 19 } 20 21 int main() 22 { 23 int i, n; 24 vector<int> v; 25 26 while (scanf("%d", &n) == 1 && n > 0) { 27 v.resize(n); 28 for (i = 0; i < n; ++i) { 29 scanf("%d", &v[i]); 30 } 31 displaceInPlace(v); 32 for (i = 0; i < n; ++i) { 33 printf((i ? " %d" : "%d"), v[i]); 34 } 35 putchar('\n'); 36 v.clear(); 37 } 38 39 return 0; 40 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)