📌  相关文章
📜  通过用它们的绝对最大值替换相邻的相反符号对来减少数组

📅  最后修改于: 2022-05-13 01:56:15.861000             🧑  作者: Mango

通过用它们的绝对最大值替换相邻的相反符号对来减少数组

给定一个大小为N的数组arr[] ,如果两个符号相反的元素相邻,任务是通过重复执行以下操作来找到最终数组:

  • 从数组中删除两个相反的符号元素,并插入具有最大绝对值的元素及其符号。
  • 如果两个元素具有相同的绝对值,则两者都将从数组中删除。

例子:

方法:可以通过以下思路解决问题:

请看下图以获得更好的理解:

按照下面提到的步骤来实施该方法:

  • 声明一个堆栈来保存数组元素。
  • 遍历数组,如果元素为正,直接压栈。
  • 否则,如果当前 arr[i] 为负,则
    • 尝试从堆栈中弹出所有为的较小元素,说明绝对值较小的元素已被丢弃。
    • 如果当前元素和栈顶相等且栈顶为,则从栈中弹出,说明两个值相等但符号相反的元素已被丢弃。
    • 最后,如果堆栈为空或最后一个元素为负数,则将当前arr[i]元素压入堆栈。因为所有剩余的元素都会有一个负号。
  • 最后,返回堆栈,显示剩余的元素。

下面是上述方法的实现:

C++
// C++ code to implement the approach
#include 
using namespace std;
 
class Solution {
  public:
  // Function to find the remaining elements
  vector solve(vector& arr)
  {
 
    // Stack to store elements
    vector st;
 
    // Traverse entire array
    for (auto element : arr) {
 
      // If positive element,
      // directly push
      if (element >= 0)
        st.push_back(element);
 
      else {
        // Pop all the smaller elements
        // moving in the right direction
        while (st.size() > 0 && st.back() >= 0
               && abs(element) > st.back())
          st.pop_back();
 
        // Top of stack and current
        // element same value and top of
        // stack moving in right direction
        if (st.size() > 0 && st.back() >= 0
            && st.back() == abs(element))
          st.pop_back();
 
        // No more elements remaining or
        // remaining elements
        // moving in left direction
        else if (st.size() == 0 || st.back() < 0)
          st.push_back(element);
      }
    }
    // Finally return stack
    return st;
  }
};
 
// Driver code
int main()
{
  Solution obj;
  vector arr = { 5, -5, -2, -10 };
 
  vector ans = obj.solve(arr);
  for (auto x : ans)
    cout << x << " ";
 
  return 0;
}
 
// This code is contributed by rakeshsahni


Python3
# Python code to implement the approach
 
class Solution:
    # Function to find the remaining elements
    def solve(self, arr):
 
        # Stack to store elements
        stack = []
 
        # Traverse entire array
        for element in arr:
 
            # If positive element,
            # directly push
            if (element >= 0):
                stack.append(element)
 
            else:
                # Pop all the smaller elements
                # moving in the right direction
                while(stack and stack[-1] >= 0 \
                      and abs(element) > stack[-1]):
                    stack.pop()
 
                # Top of stack and current
                # element same value and top of
                #  stack moving in right direction
                if (stack and stack[-1] >= 0 \
                    and stack[-1] == abs(element)):
                    stack.pop()
 
                # No more elements remaining or
                # remaining elements
                # moving in left direction
                elif(len(stack) == 0 \
                     or stack[-1] < 0):
                    stack.append(element)
 
        # Finally return stack
        return stack
 
# Driver code
if __name__ == '__main__':
    obj = Solution()
    arr = [5, -5, -2, -10]
    ans = obj.solve(arr)
    for x in ans:
        print(x, end = " ")


Javascript



输出
-2 -10 

时间复杂度: O(N)
辅助空间: O(N)