给定一维数组,求数组中 从左往右 每个数字 第一次 出现的位置。如果是 第一次 出现则返回 -1。
示例:
输入:[1,3,1,2,1]
输出:[-1,-1,0,-1,0]
解释:数字 1 出现了三次,第一次出现的位置是 0,所以除了 0 位置是 -1,其他数字 1 对应的位置答案均为 0。
暴力法
class Solution {public int[] find_left_repeat_num(int[] nums) {int[] res = new int[nums.length];for (int i = 0; i < nums.length; i++) {int find = -1;for (int j = 0; j < i; j++) {if (nums[j] == nums[i]) {find = j;break;}}res[i] = find;}return res;}}
hashmap
class Solution {public int[] find_left_repeat_num(int[] nums) {Map<Integer, Integer> map = new HashMap();int len = nums.length;int[] ret = new int[len];for (int i = 0; i < len; i++) {if (!map.containsKey(nums[i])) {// 该元素是第一次出现ret[i] = -1;map.put(nums[i], i);} else {// 该元素已经出现过ret[i] = map.get(nums[i]);}}return ret;}}
