Java程序在K左旋转后查找数组的第M个元素
给定非负整数K 、 M和具有N个元素的数组arr[]在K次左旋转后找到数组的第M个元素。
例子:
Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1
Output: 5
Explanation:
The array after first left rotation a1[ ] = {4, 5, 23, 3}
The array after second left rotation a2[ ] = {5, 23, 3, 4}
st element after 2 left rotations is 5.
Input: arr[] = {1, 2, 3, 4, 5}, K = 3, M = 2
Output: 5
Explanation:
The array after 3 left rotation has 5 at its second position.
Naive Approach:想法是执行左旋转操作K次,然后找到最终数组的第M个元素。
时间复杂度: O(N * K)
辅助空间: O(N)
- 如果数组旋转N次,它会再次返回初始数组。
For example, a[ ] = {1, 2, 3, 4, 5}, K=5 then the array after 5 left rotation a5[ ] = {1, 2, 3, 4, 5}.
因此,第 K 次旋转后的数组中的元素与原始数组中索引K%N处的元素相同。
- K左旋转后数组的第M个元素是
{ (K + M – 1) % N }th
原始数组中的元素。
下面是上述方法的实现:Java
// Java program for the above approach import java.util.*; class GFG{ // Function to return Mth element of // array after k left rotations public static int getFirstElement(int[] a, int N, int K, int M) { // The array comes to original state // after N rotations K %= N; // Mth element after k left rotations // is (K+M-1)%N th element of the // original array int index = (K + M - 1) % N; int result = a[index]; // Return the result return result; } // Driver code public static void main(String[] args) { // Array initialization int a[] = { 3, 4, 5, 23 }; // Size of the array int N = a.length; // Given K rotation and Mth element // to be found after K rotation int K = 2, M = 1; // Function call System.out.println(getFirstElement(a, N, K, M)); } } // This code is contributed by divyeshrabadiya07
输出:5
时间复杂度: O(1)
辅助空间: O(1)请参考完整的文章 Find the Mth element of the Array after K left rotations 了解更多详情!
有效方法:要优化问题,请注意以下几点: