LeetCode1

1 两数之和

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();//存数值与下标
        for(int i=0; i<length; i++){
            int num = target - nums[i];
            if(hash.containsKey(num)){
                return new int[]{hash.get(num),i};
            }
            hash.put(nums[i],i);
        }
        return null;
    }
}

target - num 看Map中是否存在值,存在就返回下标

3 无重复字符的最长子串

输入: s = "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

例子:'cdd' 'abba'
class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> noRepeat = new HashSet<>();
        int left = 0;
        int right = 0;
        int max = 0;
        for(; left<s.length(); left++){
            if(left != 0)
                noRepeat.remove(s.charAt(left-1));

            while(right<s.length() && !noRepeat.contains(s.charAt(right))){
                noRepeat.add(s.charAt(right));
                right++;
            }

            max = Math.max(max, right-left);
        }

        return max;
    }
}

左指针for循环移动,每一次移动右指针都得循环整个数组,并且判断Set中是否有重复,如果有就算长度
(滑动窗口,左指针在不断递增时,右指针也是不断递增的。因为如果第一轮下标是0-5,那当下标变为1时,1-5肯定是不重复的,所以右指针也是递增)

88 合并两个有序数组

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出:[1,2,2,3,5,6]
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        // three pointers: m-1, n-1, m+n-1
        int right1 = m-1;
        int right2 = n-1;
        int length = nums1.length-1;
        while(right1>=0 && right2>=0){
            nums1[length--] = nums1[right1] > nums2[right2] ? nums1[right1--] : nums2[right2--];
        }
        System.arraycopy(nums2, 0, nums1, 0, right2+1);
    }
}

三个指针,两个分别指nums1的值为3的位置,和最后一位。一个指nums2的最后一位
首先两个数组的最大值比较,6>3就将6放在nums1最后一位,指针向前移...

136 只出现一次的数字

输入: [4,1,2,1,2]
输出: 4

输入: [2,2,1]
输出: 1
class Solution {
    public int singleNumber(int[] nums) {
        int target = 0;
        for(int i : nums){
            target ^= i;
        }
        return target;
    }
}

异或

169 多数元素

输入:[3,2,3]
输出:3

输入:[2,2,1,1,1,2,2]
输出:2
class Solution {
    public int majorityElement(int[] num) {
        int major = num[0];
        int count = 1;
        for (int i = 1; i < num.length; i++) {
            if (count == 0) {
                //前面都消完了,在重新赋值
                count++;
                major = num[i];
            } else if (major == num[i]) {
                //自己人,count就加1
                count++;
            } else {
                //不是自己人就同归于尽,消掉一个
                count--;
            }
        }
        return major;
    }
}

摩尔投票法,力扣解析里的

posted @ 2020-12-08 12:58  lwxx  阅读(87)  评论(0)    收藏  举报