@@ -35,3 +35,42 @@ class Solution {
35
35
return ans;
36
36
}
37
37
};
38
+
39
+ // without actually flipping
40
+ // official solution
41
+ // time: O(N^2), space: O(N)
42
+ // Runtime: 8 ms, faster than 69.75% of C++ online submissions for Pancake Sorting.
43
+ // Memory Usage: 8.8 MB, less than 83.33% of C++ online submissions for Pancake Sorting.
44
+ class Solution {
45
+ public:
46
+ vector<int > pancakeSort (vector<int >& A) {
47
+ vector<int > ans;
48
+ int N = A.size ();
49
+
50
+ vector<int > indices (N);
51
+ iota (indices.begin (), indices.end (), 1 );
52
+ // the larget the former
53
+ sort (indices.begin (), indices.end (),
54
+ [&A](const int i, const int j){return A[i-1 ] > A[j-1 ];});
55
+ // copy(indices.begin(), indices.end(), ostream_iterator<int>(cout, " "));
56
+ // cout << endl;
57
+
58
+ for (int index : indices){
59
+ // don't actually reverse the vector, but simulate it
60
+ // cout << index << "->";
61
+ for (int flip : ans){
62
+ if (index <= flip){
63
+ // flip at flip'th position, so index'th position is affected
64
+ // old position + new position = flipped vector's size + 1
65
+ index = flip + 1 - index ;
66
+ }
67
+ }
68
+ // cout << index << endl;
69
+ // now index becomes the true index after serveral flipping
70
+ ans.push_back (index );
71
+ ans.push_back (N--);
72
+ }
73
+
74
+ return ans;
75
+ }
76
+ };
0 commit comments