Untitled
// [-3, -2, -1] // [1, 2, 3] std::vector<int> quadrat(std::vector<int> vec) { if (vec.size() == 0) { return vec; } int startPosSignChanged = -1; int endPosSignChanged = 0; for (int i = 1; i < vec.size(); i++) { if (sign(vec[i]) != sign(vec[i-1])) { if (vec[i] == 0) { startPosSignChanged = i; endPosSignChanged = i; } else { if (vec[i-1] == 0) { endPosSignChanged = i - 1; } else { startPosSignChanged = i-1; endPosSignChanged = i; } } } } if (vec[vec.size() - 1] == 0) { endPosSignChanged = vec.size() - 1; } else { if (vec[vec.size() - 1] < 0) { startPosSignChanged = vec.size() - 1; endPosSignChanged = vec.size(); } } std::vector<int> vecSorted(vec.size()); size_t writePos = 0; if (startPosSignChanged >= 0) { if (vec[startPosSignChanged] == 0) { for (int i = 0; i < (endPosSignChanged - startPosSignChanged + 1); i++) { vecSorted[writePos] = 0; writePos++; } startPosSignChanged--; endPosSignChanged++; } } while((startPosSignChanged > -1) && (endPosSignChanged < vec.size())) { if (abs(vec[startPosSignChanged] > vec[endPosSignChanged])) { vecSorted[writePos] = vec[endPosSignChanged] * vec[endPosSignChanged]; endPosSignChanged++; } else { vecSorted[writePos] = vec[startPosSignChanged] * vec[startPosSignChanged]; startPosSignChanged--; } writePos++; } while(startPosSignChanged > -1) { vecSorted[writePos] = vec[startPosSignChanged] * vec[startPosSignChanged]; startPosSignChanged--; writePos++; } while(endPosSignChanged < vec.size()) { vecSorted[writePos] = vec[endPosSignChanged] * vec[endPosSignChanged]; endPosSignChanged++; writePos++; } return vecSorted; }
Leave a Comment