LeetCode中的數據結構1:數組

數組問題要明確變量的定義,並全程保持其定義,維護循環不變量。

維護循環不變量

283 Move Zeroes
https://leetcode.com/problems/move-zeroes/
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

public void moveZeroes(int[] nums) {
    if (nums == null) {
        return;
    }
    int j = 0;
    for (int i=0; i<nums.length; i++) {
        if (nums[i] != 0) {
            nums[j++] = nums[i];
        } 
    }
    for (; j<nums.length; j++) {
        nums[j] = 0;
    }   
}    

27 Remove Element
https://leetcode.com/problems/remove-element/
Given an array nums and a value val, remove all instances of that value in-place and return the new length.

public int removeElement(int[] nums, int val) {
    int j=0;
    for (int i=0; i<nums.length; i++) {
        if (nums[i] != val) {
            nums[j] = nums[i];
            j++;
        }
    }
    return j;
}   

26 Remove Duplicates from Sorted Array
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

public int removeDuplicates(int[] nums) {
    int j=0;
    for (int i=0; i<nums.length; i++) {
        if (i==nums.length-1) {
            nums[j] = nums[i];
            j++;
            return j;
        }
        if (nums[i] != nums[i+1]) {
            nums[j] = nums[i];
            j++;
        }
    }
    return j;
}

80 Remove Duplicates from Sorted Array II
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
亂寫一通,居然通過了。而且Runtime: 0 ms, faster than 100.00%,Memory Usage: 37.2 MB, less than 100.00%。

public int removeDuplicates(int[] nums) {
    int i=0;
    int j=0;
    while(i<nums.length) {
        if (i+2>=nums.length) {
            nums[j] = nums[i];
            i++;
            j++;
            continue;
        }
        if (nums[i+2] != nums[i]) {
            nums[j] = nums[i];
            j++;
        }
        i++;
    }
    return j;
}
Partition思路

75 Sort Colors
https://leetcode.com/problems/sort-colors/
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

public void sortColors(int[] nums) {
    int j = 0;
    int k = nums.length-1;
    for (int i=0; i<=k; i++) {
        if (nums[i] == 0) {
            swap(nums, i, j++);
        } else if (nums[i] == 2) {
            swap(nums, i--, k--);
        }
    }
}
private void swap(int[] nums, int i, int j) {
    int c = nums[i];
    nums[i] = nums[j];
    nums[j] = c;
}

88 Merge Sorted Array
https://leetcode.com/problems/merge-sorted-array/
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

public void merge(int[] nums1, int m, int[] nums2, int n) {
    int i1 = m-1;
    int i2 = n-1;
    for(int i=m+n-1; i>=0; i-- ){ 
        if (i2<0 && i1>=0) {
            nums1[i] = nums1[i1];
            i1--;
            continue;
        } else if (i1<0 && i2>=0) {
            nums1[i] = nums2[i2];
            i2--;
            continue;
        }
        if (nums1[i1] >= nums2[i2]) {
            nums1[i] = nums1[i1];
            i1--;
        } else {
            nums1[i] = nums2[i2];
            i2--;
        }
    }
}

215 Kth Largest Element in an Array
https://leetcode.com/problems/kth-largest-element-in-an-array/
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

public int findKthLargest(int[] nums, int k) {
        int r = nums.length-1;
        k = nums.length - k + 1; 
        return findKthLargestRange(nums, k, 0 ,r);
    }
    
    private int findKthLargestRange(int[] nums, int k, int l , int r) {
        int mid = l + (r-l)/2;
        swap(l, mid, nums);
        int i=l+1;
        int j=r;
        int val = nums[l];
        while (i<=j) {
            if (nums[i]>val) {
                swap(i, j, nums);
                j--;
            } else {
                i++;
            }
        }
        swap(j, l ,nums);
        if (j==k-1) {
            return nums[j];
        } else if (j<k-1) {
            return findKthLargestRange(nums, k, j+1 ,r);
        } else {
            return findKthLargestRange(nums, k, l ,j-1);
        }
    }
    
    private void swap(int i, int j, int[] arr) {
        int c = arr[i];
        arr[i] = arr[j];
        arr[j] = c;
    }
對撞指針

167 Two Sum II - Input array is sorted
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

public int[] twoSum(int[] numbers, int target) {
	int lft = 0;
    int rgt = numbers.length-1;
    while(lft < rgt){
        if(numbers[lft] + numbers[rgt] > target){
            rgt--;
        } else if(numbers[lft] + numbers[rgt] < target){
            lft++;
        } else {
            int[] ans = {lft+1, rgt+1};
            return ans;
        } 
    }
    throw new RuntimeException("There is no answer such that they add up to a specific target number.");
}

125 Valid Palindrome
https://leetcode.com/problems/valid-palindrome/
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

public boolean isPalindrome(String s) {
    // 0-9 48-57
    // A-Z 65-90
    // a-z 97-122
    int i = 0;
    int j = s.length()-1;
    String sb = s.toLowerCase();
    
    while(i<j){
        int charAtI = sb.charAt(i);
        int charAtJ = sb.charAt(j);
        if(charAtI<48 || (charAtI>57 && charAtI<97) || charAtI>122){
            i++;
            continue;
        }
        if(charAtJ<48 || (charAtJ>57 && charAtJ<97) || charAtJ>122){
            j--;
            continue;
        }
        if(charAtI == charAtJ){
            i++;
            j--;
        }else{
            return false;
        } 
    }
    return true;        
}

345 Reverse Vowels of a String
https://leetcode.com/problems/reverse-vowels-of-a-string/
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

public String reverseVowels(String s) {
    StringBuffer sb = new StringBuffer(s);
    int i = 0;
    int j = sb.length()-1;
    Set<Character> vowels = new HashSet<>();
    vowels.add('A');
    vowels.add('E');
    vowels.add('I');
    vowels.add('O');
    vowels.add('U');
    vowels.add('a');
    vowels.add('e');
    vowels.add('i');
    vowels.add('o');
    vowels.add('u');
    
    while(i<j){
        char charAtI = sb.charAt(i);
        char charAtJ = sb.charAt(j);
        if(vowels.contains(charAtI) && vowels.contains(charAtJ)){
            sb.setCharAt(i, charAtJ);
            sb.setCharAt(j, charAtI);
            i++;
            j--;
        } else if(vowels.contains(charAtI)) {
            j--;
        } else if(vowels.contains(charAtJ)) {  
            i++;
        } else {
            i++;
            j--;
        }
    }
    return sb.toString();
}

11 Container With Most Water
https://leetcode.com/problems/container-with-most-water/
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

public int maxArea(int[] height) {
    int area = 0;
    int lft = 0;
    int rgt = height.length-1;
    while(lft<rgt){
        int h = height[lft]<height[rgt]?height[lft]:height[rgt];
        int w = rgt-lft;
        area = h*w>area?h*w:area;
        if(height[lft]<height[rgt]){
            lft++;
        } else {
            rgt--;
        }
    }
    return area;
}
滑動窗口

209 Minimum Size Subarray Sum
https://leetcode.com/problems/minimum-size-subarray-sum/
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.

public int minSubArrayLen(int s, int[] nums) {
    // 區間[lft,rgt]
    int lft = 0;
    int rgt = -1;
    int minSize = nums.length + 1;
    int sum = 0;
    while(lft<nums.length-1){
        if(rgt<nums.length-1 && sum<s){
            rgt++;
            sum += nums[rgt];
        }else{
            if(sum>=s){
                minSize = (rgt-lft+1)<minSize?(rgt-lft+1):minSize;
            }
            sum -= nums[lft];
            lft++;
        }
    }
    if(minSize == nums.length + 1){
        return 0;
    }
    return minSize;
}

3 Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.

public int lengthOfLongestSubstring(String s) {   
    Set<Character> set = new HashSet<>();
    int i=0;
    int j=0;
    int l=0;
    while (i<s.length() && j<s.length()) {
        if (!set.contains(s.charAt(i))) {
            set.add(s.charAt(i++));
            l=Math.max(l,i-j);
        } else {
            set.remove(s.charAt(j++));
        }
    }
    return l;
}

438 Find All Anagrams in a String
https://leetcode.com/problems/find-all-anagrams-in-a-string
Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.

public List<Integer> findAnagrams(String s, String p) {
    List<Integer> list = new ArrayList<>();
    if (s==null || s.length()==0 || p==null || p.length()==0) {
        return list;
    }
    char[] hash = new char[256];
    for (char c : p.toCharArray()) {
        hash[c]++;
    } 
    int right=0, left=0, count=0;
    while(right<s.length()) {
        if (hash[s.charAt(right)]>0) {
            hash[s.charAt(right)]--;
            right++;
            count++;
        } else {
            hash[s.charAt(left)]++;
            left++;
            count--;
        }
        if (count == p.length()) {
            list.add(left);
        }
    }
    return list;
}

76 Minimum Window Substring
https://leetcode.com/problems/minimum-window-substring/
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Hard模式,也可以用滑動窗口解,但因爲我有Hard恐懼症,暫時沒做。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章