https://www.lintcode.com/problem/longest-prefix-of-array/description
给定一个数组 A A A,再给定两个数 x x x和 y y y,求最长的 A A A前缀 A [ 0 : i ] A[0:i] A[0:i]使得 x x x和 y y y在其中的出现次数相等,且出现次数都大于 0 0 0。
用两个变量记录前缀里两个数字出现次数即可。代码如下:
public class Solution { /** * @param X: a integer * @param Y: a integer * @param nums: a list of integer * @return: return the maximum index of largest prefix */ public int LongestPrefix(int X, int Y, int[] nums) { // write your code here int countX = 0, countY = 0; int res = -1; for (int i = 0; i < nums.length; i++) { if (nums[i] == X) { countX++; } if (nums[i] == Y) { countY++; } if (countX == countY && countX > 0) { res = Math.max(res, i); } } return res; } }时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。