● 242.有效的字母异位词 ● 349. 两个数组的交集 ● 202. 快乐数

242.有效的字母异位词 

create Arraylist to store String, 比较里面的element,s++,i--,判断条件,如果最后只有0,就是对的。

349两个数组的交集

class Solution {

    public int[] intersection(int[] nums1, int[] nums2) {

        // Create a HashSet to store unique elements from nums1

        Set<Integer> set = new HashSet<>();

        for (int num : nums1) {

            set.add(num);

        }


        // Create a List to store the intersection elements

        List<Integer> intersection = new ArrayList<>();

        for (int num : nums2) {

            if (set.contains(num)) {

                intersection.add(num);

                set.remove(num); // Remove the element from the set to avoid duplicates

            }

        }


        // Convert the List to an array

        int[] result = new int[intersection.size()];

        for (int i = 0; i < intersection.size(); i++) {

            result[i] = intersection.get(i);

        }


        return result;

    }

}

//O(m + n)


202

class Solution {

    public boolean isHappy(int n) {

        Set<Integer> set = new HashSet<>();


        while (n != 1) {

            if (set.contains(n)) {

                return false;

            }


            set.add(n);

            n = calculateSquareSum(n);

        }


        return true;

    }


    private int calculateSquareSum(int n) {

        int sum = 0;

        while (n > 0) {

            int digit = n % 10;

            sum += digit * digit;

            n /= 10;

        }

        return sum;

    }

}

If n is already in the set, return false (number is not happy).

Add n to the set.

Calculate the sum of the squares of the digits of n.

Set n to be the sum calculated in the previous step.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容