Composite模式拓展

Composite模式除了作为文件夹操作,还能怎么操作?

答:可以作为Html中的ul ol 以及li 这些列表标签

在Composite模式的基础上添加方法displayFullName 来显示完整路径,如:/root/var/xxx

Entry添加

Entry parent;


public void displayFullName() {
  StringBuffer fullname = new StringBuffer();
  Entry entry = this;
  do {
    fullname.insert(0, "/" + entry.getName());
    entry = entry.parent;
  } while (entry != null)
  return fullName;
}

Directory添加

Entry add(Entry entry) {
  ...
  entry.parent = this;
  ...
}

充电宝项目——根据腾讯地图api获取地址的经纬度

service:

@Resource
private RestTemplate restTemplate;

...

String url = "https://apis.map.qq.com/ws/geocoder/v1/?address={address}&key={key}";

// 使用map存储参数
Map<Stirng, Stirng> map = new HashMap<>();
map.put("address", keyword);
map.put("key", key); // 此key为官网后台所得

// 发送Get请求
JSONObject response = restTemplate.getForObject(url, JSONObject.class, map);

//返回第一条最佳线路
JSONObject result = response.getJSONObject("result");
System.out.println(result.toJSONString());
return result.getJSONObject("location");

其实还完成了一个增删改查的基础构建,懒得写了

算法——两数之和

哈哈,又滚回来写简单算法题了,我太菜了。

这题的重点在对 target 的理解,两数之和可以是 nums[i] + nums[j],也可以 nums[j] - target = 0也是。

因此,可以将nums[j] - target存储为key,每次检查

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i]))
                return new int[] { map.get(target - nums[i]), i };
            map.put(nums[i], i);
        }
        return new int[0];
    }
}