在這個問題中,我們給了一個大小為N的陣列arr[]。我們的任務是在數組中可能的移動後找到左指標的索引。
我們有兩個指針,一個是左邊指針,另一個是右邊指針。
左指標從索引0開始,值遞增。
右指標從索引(n-1)開始,值遞減。
如果左指標的和小於右指標的和,則指標的值增加,否則指標的值會減少。並且和的值會更新。
讓我們透過一個例子來理解這個問題,
Input : arr[] = {5, 6, 3, 7, 9, 4} Output : 2
#Explanation −
的中文翻譯為:Explanation −
leftPointer = 0 -> sum = 5, rightPointer = 5 -> sum = 4. Move rightPointer leftPointer = 0 -> sum = 5, rightPointer = 4 -> sum = 13. Move leftPointer leftPointer = 1 -> sum = 11, rightPointer = 4 -> sum = 13. Move leftPointer leftPointer = 2 -> sum = 14, rightPointer = 4 -> sum = 13. Move rightPointer leftPointer = 2 -> sum = 14, rightPointer = 3 -> sum = 20. Move rightPointer Position of the left pointer is 2.
透過根據和的大小移動左指標和右指標來解決問題。然後檢查左指針是否比右指針大1。
程式範例,說明我們解決方案的工作原理
#include <iostream> using namespace std; int findIndexLeftPointer(int arr[], int n) { if(n == 1) return 0; int leftPointer = 0,rightPointer = n-1,leftPointerSum = arr[0], rightPointerSum = arr[n-1]; while (rightPointer > leftPointer + 1) { if (leftPointerSum < rightPointerSum) { leftPointer++; leftPointerSum += arr[leftPointer]; } else if (leftPointerSum > rightPointerSum) { rightPointer--; rightPointerSum += arr[rightPointer]; } else { break; } } return leftPointer; } int main() { int arr[] = { 5, 6, 3, 7, 9, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout<<"The index of left pointer after moving is "<<findIndexLeftPointer(arr, n); return 0; }
The index of left pointer after moving is 2
以上是在C++中,找到數組中可能移動後左指標的索引的詳細內容。更多資訊請關注PHP中文網其他相關文章!