0% found this document useful (0 votes)
19 views4 pages

C++ Array and List Algorithms

Uploaded by

Hello Duy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

C++ Array and List Algorithms

Uploaded by

Hello Duy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

1.

int buyCar(int* nums, int length, int k) {


sort(nums, nums + length);
int max = 0, sum = 0;
for (int i = 0; i < length; i++) {
sum += nums[i];
if (sum > k) break;
max++;
}
return max;
}

2.
bool consecutiveOnes(vector<int>& nums) {
// STUDENT ANSWER
bool a = false;
vector<int> check;
if ([Link]() == 0) return true;
for (int i = 0; i < [Link](); i++) {
if (nums[i] == 1) {
if ([Link]() == 0 && a == true) {
return false;
}
check.push_back(1);
if ([Link]() > 1) {
a = true;
}
} else {
[Link]();
}
}
return a;
}

3.
int equalSumIndex(vector<int>& nums) {
// STUDENT ANSWER
int right = 0;
int left = 0;
for (int i = 1; i < [Link](); i++) {
right += nums[i];
}
if (left == right) return 0;
for (int i = 1; i < [Link](); i++) {
left += nums[i - 1];
right -= nums[i];
if (left == right) {
return i;
}
}
return -1;
}

4.
int longestSublist(vector<string>& words) {
if ([Link]() == 0) return 0;
vector<char> check;
check.push_back(words[0][0]);
int count = 1;
int max = 0;
for (int i = 1; i < [Link](); i++) {
if (words[i][0] == check[0]) {
count++;
}
else {
[Link]();
check.push_back(words[i][0]);
count = 1;
}
if (count >= max) max = count;
}
return max;
}

5.
template <class T>
void ArrayList<T>::add(T e) {
/* Insert an element into the end of the array. */
ensureCapacity(count);
data[count] = e;
count++;
}

template<class T>
void ArrayList<T>::add(int index, T e) {
/*
Insert an element into the array at given index.
if index is invalid:
throw std::out_of_range("the input index is out of range!");
*/
ensureCapacity(count + 1);
count++;
for (int i = count - 1; i >= index; i--) {
data[i + 1] = data[i];
}
data[index] = e;
}

template<class T>
int ArrayList<T>::size() {
/* Return the length (size) of the array */
return count;
}

template<class T>
void ArrayList<T>::ensureCapacity(int cap) {
/*
if cap == capacity:
new_capacity = capacity * 1.5;
create new array with new_capacity
else: do nothing
*/
if (cap == capacity) {
int new_capacity = capacity * 1.5;
T* new_data = new T[new_capacity];
for (int i = 0; i < count; i++) {
new_data[i] = data[i];
}
delete[] data;
data = new_data;
capacity = new_capacity;
}
}

6.
template<class T>
T ArrayList<T>::removeAt(int index) {
/*
Remove element at index and return removed value
if index is invalid:
throw std::out_of_range("index is out of range");
*/
if (index < 0 || index > count - 1) {
throw out_of_range("index is out of range");
}
int temp = data[index];
for (int i = index; i < count; i++) {
data[i] = data[i + 1];
}
count--;
return temp;
}

template<class T>
bool ArrayList<T>::removeItem(T item) {
/* Remove the first apperance of item in array and return true, otherwise
return false */
int index = -1;
for (int i = 0; i < count; i++) {
if (data[i] == item) {
index = i;
break;
}
if (i == count - 1) {
return false;
}
}
removeAt(index);
return true;
}

template<class T>
void ArrayList<T>::clear() {
/*
Delete array if array is not NULL
Create new array with: size = 0, capacity = 5
*/
if (data != NULL) {
delete[] data;
}
capacity = 5;
count = 0;
T* new_data = new T(capacity);
data = new_data;
}

7.
vector<int> updateArrayPerRange(vector<int>& nums, vector<vector<int>>& operations)
{
for (size_t i = 0; i < [Link](); i++) {
int L = operations[i][0];
int R = operations[i][1];
int add = operations[i][2];
for (int j = L; j <= R; j++) {
nums[j] += add;
}
}
return nums;
}

Common questions

Powered by AI

When the input vector `words` is empty, the `longestSublist` function directly returns 0. This condition is checked at the start of the function to handle edge cases efficiently, ensuring that no further operations attempt to process an empty vector and avoiding potential errors or unnecessary computations .

The `ArrayList` class functions include adding elements (either at the end or at a given index), removing elements, and managing capacity. To add an element, it checks if the current capacity suffices using `ensureCapacity`, which increases capacity by 1.5 times if needed, reallocating memory to accommodate more elements. Adding at a specific index shifts existing elements to make space, while removing elements involves shifting elements to fill the gap caused by removal. The internal capacity ensures efficient memory usage without constantly resizing the array .

The `consecutiveOnes` function returns `false` if there is a non-empty array containing 1s where the 1s do not appear consecutively after the first sequence. Initially, if the first detected sequence of 1s is followed by any other sequence of 1s with another number in between, the function will identify this as a new sequence and return `false`. This behavior happens because the presence of a non-1 between 1s resets the list and checks for a pattern continuation .

The `longestSublist` function identifies the longest contiguous sublist of strings that all start with the same character. It initializes a check vector to keep track of the current starting character of the sublist. As it iterates through the words, it compares the first character of each word with the tracked starting character. If they match, the count increases. When it encounters a word that starts with a different character, it resets the check vector and count to the new character. The function maintains a maximum length variable, which represents the longest sublist encountered and returns this value .

The `buyCar` function optimizes car purchases by first sorting the array of car prices in ascending order. This sorting ensures that cheaper cars are considered first, maximizing the number of cars bought before the budget `k` is exceeded. By iteratively summing the prices starting from the lowest, the function allows a sequential and controlled increase until no further cars can be added without breaching the budget, which aligns with an optimization strategy for maximum acquisition .

The `buyCar` function aims to calculate the maximum number of cars that can be bought without exceeding a given budget `k`. It first sorts the array of car prices, then iteratively adds the price of each car to a running total (`sum`) until adding another car price would exceed the budget. This approach ensures the maximum number of affordable cars are selected. The function returns the count of cars (`max`) that can be bought under budget .

Upon invoking the `clear` method on an `ArrayList`, all existing data is deleted, effectively resetting the array. After clearing, a new array is created with a predefined initial capacity of 5 and the size is set to 0, indicating an empty array. This resets the `ArrayList` to its default state, essentially as if it were newly instantiated with no elements .

The `updateArrayPerRange` function modifies an input array according to a list of operations, where each operation specifies a range and an additive value. For each operation, it iterates through the specified range of indices (`L` to `R`) and increments each element within by a given addend. This changes each selected index in the range to reflect the influence of the specified operation .

The `removeItem` function removes the first occurrence of a specified item from the `ArrayList`. It iterates through the data array to find the first index of the item. If the item is found, `removeAt(index)` is called to eliminate the element at that position and the function returns `true`. If the loop completes without finding the item, the function returns `false`, indicating the item was not present in the array .

The `equalSumIndex` function is designed to find an index `i` in the array such that the sum of elements to the left of `i` is equal to the sum of elements to the right. It initializes separate sums for the right and left sides of the index. Initially, the right sum contains all elements except the first, while the left sum starts at zero. As it iterates through the array, it progressively shifts elements from the right sum to the left sum. When these sums are equal, it returns the index `i`. If no such index exists where both sums are equal, it returns -1 .

You might also like