美文网首页
Leetcode-Java(二十九)

Leetcode-Java(二十九)

作者: 文哥的学习日记 | 来源:发表于2018-07-02 23:20 被阅读57次

    283. Move Zeroes

    遍历

    class Solution {
        public void moveZeroes(int[] nums) {
            int index = 0;
            for(int i=0;i<nums.length;i++){
                if(nums[i] != 0)
                    nums[index++] = nums[I];
            }
            for(int i=index;i<nums.length;i++){
                nums[index++] = 0;
            }
        }
    }
    

    287. Find the Duplicate Number

    由于题目里限制了我们的空间复杂度只能是O(1),因此不能用set保存出现过的数字,因此这道题利用index的技巧,如果一个数出现过一次,将这个数字对应下标的数字变为负数,如果第二次遇到这个数字,那么这个数字对应下表的数字会是负数,此时直接返回该数字。

    class Solution {
        public int findDuplicate(int[] nums) {
            for(int i=0;i<nums.length;i++){
                if(nums[Math.abs(nums[i])] < 0)
                    return Math.abs(nums[I]);
                nums[Math.abs(nums[i])] = -nums[Math.abs(nums[i])];
            }
            return 0;
        }
    }
    

    290. Word Pattern

    用一个字典来保存char和string的对应关系,不过要注意第四种情况,因此在不仅要判断char在不在map的key中,同时也要判断value中是否包含当前的string。

    class Solution {
        public boolean wordPattern(String pattern, String str) {
            Map<Character,String> map = new HashMap<Character,String>();
            char[] chrs = pattern.toCharArray();
            String[] strs = str.split(" ");
            if(chrs.length!=strs.length)
                return false;
            for(int i=0;i<chrs.length;i++){
                if(!map.containsKey(chrs[i])){
                    if(map.containsValue(strs[i]))
                        return false;
                    map.put(chrs[i],strs[i]);
                }
                else{
                    if(!map.get(chrs[i]).equals(strs[i]))
                        return false;
                }
            }
            return true;
        }
    }
    

    相关文章

      网友评论

          本文标题:Leetcode-Java(二十九)

          本文链接:https://www.haomeiwen.com/subject/wsphuftx.html