easy题两道

最长公共前缀
public class LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        // 如果字符串数组为空或长度为0,返回空字符串
        if (strs == null || strs.length == 0) {
            return "";
        }
        
        // 取第一个字符串作为初始前缀
        String prefix = strs[0];
        
        // 遍历字符串数组的其他字符串
        for (int i = 1; i < strs.length; i++) {
            // 比较当前字符串与当前前缀
            while (strs[i].indexOf(prefix) != 0) {
                // 缩短前缀
                prefix = prefix.substring(0, prefix.length() - 1);
                // 如果前缀为空,返回空字符串
                if (prefix.isEmpty()) {
                    return "";
                }
            }
        }
        
        // 返回最长公共前缀
        return prefix;
    }

    public static void main(String[] args) {
        LongestCommonPrefix solution = new LongestCommonPrefix();
        String[] strs = {"flower", "flow", "flight"};
        System.out.println(solution.longestCommonPrefix(strs)); // 输出 "fl"
    }
}
两元素的和等于目标值
import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    public int[] twoSum(int[] nums, int target) {
        // 创建哈希表用于存储数值及其下标
        Map<Integer, Integer> map = new HashMap<>();
        
        // 遍历数组中的每个元素
        for (int i = 0; i < nums.length; i++) {
            // 计算目标值与当前元素的差值
            int complement = target - nums[i];
            
            // 检查该差值是否存在于哈希表中
            if (map.containsKey(complement)) {
                // 如果存在,则返回当前元素的下标和该差值对应的下标
                return new int[] { map.get(complement), i };
            }
            
            // 将当前元素及其下标存入哈希表
            map.put(nums[i], i);
        }
        
        // 如果未找到符合条件的两个数,返回空数组
        return new int[0];
    }

    public static void main(String[] args) {
        TwoSum solution = new TwoSum();
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        int[] result = solution.twoSum(nums, target);
        System.out.println("Indices: [" + result[0] + ", " + result[1] + "]"); // 输出 "Indices: [0, 1]"
    }
}
posted @ 2024-07-04 22:52  又是火星人  阅读(1)  评论(0编辑  收藏  举报