-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRankTransformOfAnArray.cpp
More file actions
110 lines (103 loc) · 2.39 KB
/
RankTransformOfAnArray.cpp
File metadata and controls
110 lines (103 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
class Solution
{
public:
vector<int> arrayRankTransform(vector<int> &arr)
{
vector<int> sorted_arr = arr;
sort(sorted_arr.begin(), sorted_arr.end());
unordered_map<int, int> myMap;
int rank = 1;
for (auto i = 0; i < sorted_arr.size(); ++i)
{
if (myMap.find(sorted_arr[i]) == myMap.end())
{
myMap[sorted_arr[i]] = rank;
rank++;
}
}
vector<int> res(arr.size());
for (auto i = 0; i < arr.size(); ++i)
{
res[i] = myMap[arr[i]];
}
//* debugging
for (auto it = myMap.begin(); it != myMap.end(); ++it)
{
cout << it->first << " " << it->second << endl;
}
cout << "\n===========\n";
for (int val : res)
{
cout << val << " ";
}
return res;
}
};
// "\n===============\n";
/*
arr = [40,10,20,30]
Output: [4,1,2,3]
*/
int main()
{
Solution sol;
vector<int> vec = {40, 10, 20, 30, 40};
sol.arrayRankTransform(vec);
return 0;
}
// private:
// vector<int> count_if_smaller(const vector<int> &v)
// {
// vector<int> result(v.size());
// transform(v.begin(), v.end(), result.begin(),
// [&](int x)
// {
// return count_if(v.begin(), v.end(), [&](int y)
// { return y < x; });
// });
// return result;s
// }
// class Solution
// {
// public:
// vector<int> arrayRankTransform(vector<int> &arr)
// {
// vector<int> sorted_arr = arr;
// sort(sorted_arr.begin(), sorted_arr.end());
// unordered_map<int, int> myMap;
// vector<int> res(arr.size());
// int rank = 1;
// for (auto i = 0; i < sorted_arr.size(); ++i)
// {
// if (sorted_arr[i] == sorted_arr[i + 1] && i < sorted_arr.size() - 1)
// {
// myMap[sorted_arr[i]] = myMap[sorted_arr[i + 1]] = rank;
// }
// else
// {
// myMap[sorted_arr[i]] = rank;
// rank++;
// }
// }
// for (auto it = myMap.begin(); it != myMap.end(); ++it)
// {
// cout << it->first << " " << it->second << endl;
// res.push_back(it->second);
// }
// cout << "\n===========\n";
// for (int num : arr)
// {
// res.push_back(num);
// }
// for (int val : res)
// {
// cout << val << " ";
// }
// return res;
// }
// };